Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add active class on a map items react

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

like image 708
Alexandre Buisson Avatar asked Jan 27 '23 08:01

Alexandre Buisson


1 Answers

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).

like image 102
Vencovsky Avatar answered Jan 29 '23 13:01

Vencovsky