After map my array, I want to add an active css class if the user clicked on 1 element.
My map prototype :
publicationsPages.map((mod, i) => (
<div onClick={e => this.addActiveClass(i, e)} className=
{`${activeClasses[i] ? "active" : "inactive"} ${classes.modcontainer}
modcontainer`}>
<p className={`${classes.menuitems} menuitems`}>
{t(`Publications.${mod.name}`).toUpperCase()}
</p>
</div>
))
I have tried with a method called addActiveClass and a state :
this.state={activeClasses: [false, false, false, false]}
addActiveClass(index) {
const result = [...this.state.activeClasses.slice(0, index), !this.state.activeClasses[index], this.state.activeClasses.slice(index + 1)];
this.setState({activeClasses: result});
}
But that does not work. Thank you in advance for your help
On the click of the element, you keep in your state the index of the selected item. In the item you can check if the index is the same as the index in the state and add the active class.
publicationsPages.map((mod, i) => (
<div
onClick={e => this.setState({activeIndex: i)}}
className= {`${i == this.state.activeIndex ? "active" : "inactive"}
>
...
</div>
))
Your default (or initial) value for activeIndex
should be -1
, then in the begging, no item will me active (if you want this).
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