After map my array, I want to add an active css class if the user clicked on 1 element.

My map prototype :, i) => (
  <div onClick={e => this.addActiveClass(i, e)} className= 
  {`${activeClasses[i] ? "active" : "inactive"} ${classes.modcontainer} 
    <p className={`${classes.menuitems} menuitems`}>

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

1 Answers

Vencovsky On Best Solutions

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., i) => (
        onClick={e => this.setState({activeIndex: i)}} 
        className= {`${i == this.state.activeIndex ? "active" : "inactive"}

Your default (or initial) value for activeIndex should be -1, then in the begging, no item will me active (if you want this).