Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

change background of one button when clicked in a loop

I have a loop of multiple buttons, I want to change the background color of only the clicked button and not all of them as it happens here :

const [clicked, setClicked] = useState(false);

<div className="flex gap-4 flex-wrap">
    {times.map((time, i) => (
            <div
                key={`time-${i}`}
                className={`${clicked ? 'bg-slate-400' : 'bg-light-gold'}`}
                onClick={() => { setClicked(true) }
             >
                    {time}
            </div>
    ))}
</div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Should check index of button clicked.

const [idClicked, setIdClicked] = useState(-1);

<div className="flex gap-4 flex-wrap">
    {times.map((time, i) => (
            <div
                key={`time-${i}`}
                className={`${idClicked === i ? 'bg-slate-400' : 'bg-light-gold'}`}
                onClick={() => { setIdClicked(i) }
             >
                    {time}
            </div>
    ))}
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading