Conditionally changing classNames in React

Let´s say you have a component that returns a bunch of divs, and that you want to conditionally set a className that changes the background color of said div on hover. How could you accomplish this? Using a flag in state (how do you get the other divs to NOT change color if that´s the case once you hover away). Haven´t really found a convincing approach in the other questions.

If you want to change the background color on hover, why not just do it in the CSS?

Because there are many divs and I want to make sure only the one being hovered changes color

Sorry, I didnt mean hover. I meant having something clicked and becoming active, AND then, when you click something else, having that active class removed and added to the new clicked element

That’s exactly what the :hover selector does: it applies only when it’s being hovered over. Doing it by hand means listening for mouseover and mouseout events, which at least for cosmetic effects like changing color, is widely seen as an antipattern in javascript.

See also https://www.w3schools.com/cssref/sel_hover.asp

Yeah. Please see the post above, I meant click and active.

See my answer in this thread:

This should be exactly what you asking for.

Thanks. But how do you check if event.target marches the one in the array? IndexOf?

Ah, sorry about that. The classNames (note the plural) attribute might come in handy there, since it’s an object with class names as the key and boolean values that indicate whether the element has that class or not. You can then either check the component state or use redux to determine the value of the selected (for example) class. I’ve only done that sort of thing with redux myself, so I couldn’t give you a quick solution here (sorry again)

When you iterate over the array of divs, you can get the active ones with the corresponding index in your active state.

Sorry, still not grasping: so a for loop in the handler with indexOf in the state array. But how do I remove the className if another elementos has it?

Look at this line:

 className={`${this.state.active[index] !== true ? 
    styles.tagNormalState : 
    styles.tagSelectedState}`}

Using a ternary operator, this will set the className for the div if it is active, when you map over your items.

I manage to solve it using an index that update the state of just that element. I f the state is active then apply the right style by using a ternary operator

Do you mind sharing the code?