I'm going through the React documentation and trying to change the condition of one element within a map based on the click of a corresponding element (associated with the same key). Using a handleClick that looks something like this:
handleClick: function(e) {
this.setState({condition: !this.state.condition});
console.log('clicked' + e);
}
I have some menu items drawn this way:
return (
<li key={i}>
<a
onClick={_this.handleClick.bind(_this, i)}
data-nav={'nav-' + el.label.en.toLowerCase()}>
{el.label.en}
</a>
</li>
);
And some submenu sections whose class I want to toggle based on click of the above:
return (
<section
className={_this.state.condition ? "active" :""}
key={i}
id={'nav-' + el.label.en.toLowerCase()}>
<ul>
<GetChildren data={el.children} />
</ul>
</section>
);
Right now, obviously, when I click the first, all elements toggle their class. For the life of me, I can't figure out how to pass the key, so that if I'm clicking on item 1, the section with key {1} gets an "active" class, and others do not. In javascript with jquery I could get at it using the data-attribute. I'm sure react has a simple way that I'm just not understanding.
You can do this by setting the active key in your state object instead of toggling a condition.
So in your handleClick
this.setState({
activeKey: e
});
then in your <section>
className={_this.state.activeKey === i ? "active" : ""}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With