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>
3
Answers
The UI should be driven by data. You need to create a button list data, each object contains the button’s label, button’s clicked status, etc…
When the button is clicked, change the value of
clicked
property of the button.codesandbox
Should check
index
of button clicked.Assuming you want to be able to have multiple clicked buttons.
You could change the useState to be an array in which you place the indexes of the pressed buttons, and remove them if you click again