alexsouye
alexsouye

Reputation: 740

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

Upvotes: 6

Views: 5509

Answers (1)

Vencovsky
Vencovsky

Reputation: 31565

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

Upvotes: 10

Related Questions