Skip to content
Advertisement

How can I toggle styles (background-color to be specific) on multiple buttons with the same class (react.js)

So I have multiple setting buttons and I need them to individually toggle their background colors

here’s a simplified jsx example

JavaScript

CSS

JavaScript

but of course this won’t work because the style would be applied to all the buttons at once.

How can I identify which one is clicked and style that specific button without having to create states and event listeners for all the buttons?

Edit – In case this wasn’t clear, I’d like to be able to toggle all the buttons independently of each other.

Advertisement

Answer

I would do something as below … most of it is self explanatory 😉

JavaScript
JavaScript
JavaScript

As per the comment below – one button toggle doesn’t un-toggle the other

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement