change background of one button when clicked in a loop

Advertisements

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 :

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>

Leave a ReplyCancel reply