I am new in React and face an issue.
I have several divs and when a div is clicked, I want to add a new class in this div only.
The issue is when I click on a class, it adds a new class in this div, but it also adds new classes in all other divs.
Please take a look at my code below and please give me a hand.
Thanks
export default function Toggle() {
const [hoverToggle, setHoverToggle] = useState();
const toggleIt = () => {
setHoverToggle(!hoverToggle);
};
return (
<>
<div
onClick={toggleIt}
className={`${hoverToggle ? "getClick" : "noClick"}`}
>
This is DIV 1
</div>
<div
onClick={toggleIt}
className={`${hoverToggle ? "getClick" : "noClick"}`}
>
This is DIV 2
</div>
<div
onClick={toggleIt}
className={`${hoverToggle ? "getClick" : "noClick"}`}
>
This is DIV 3
</div>
</>
)
3
Answers
Your variable hoverToggle is shared with all divs.
Maybe try this :
This way each created div will have its separate state.
The reason why new classes are being added to all other divs is that you are using the same useState() and toggleIt function for all the divs. Whenever a click occurs in any of the divs, the toggleIt function gets called, which causes a change in the hoverToggle. Since you are only using one hoverToggle for the three divs, this change affects all of them. I hope this explanation is clear enough.
Try this out, I believe it will work out fine.
As the same state is used in all three
div
elements, regardless of which one is clicked, the CSS class is applied to all of them.Instead of using a boolean value for the state, you can use a numeric value to target only the clicked element.
This should give you the toggle behavior you are looking for. The
getClick
class is added if the value ofhoverToggle
matches theindex
of the clicked element, otherwise it is replaced by thenoClick
class.Also note that when an item is clicked twice in a row, the state is reset to its initial value of
null
to create the toggle effect.