Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: using handleclick to toggle class of mapped element by key

Tags:

reactjs

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.

like image 704
dilettante Avatar asked Dec 28 '25 09:12

dilettante


1 Answers

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" : ""}
like image 177
Deryck Avatar answered Dec 30 '25 23:12

Deryck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!