Darren
Darren

Reputation: 2290

Add 'active' class to a mapped item causes all items to have class active

How can I onClick add the class to only the item clicked? The below code is sufficient in adding/removing the class active but adds to all items in mapped `array

{tourDetails.map(({ node: questions })=> (
  <div key={questions.id} className="toggle">
    <div onClick={this.handleToggleActive} className={`toggle-title ${this.state.questionActive ? 'active' : ''}`}>
      <h3><i></i><span className="title-name">{questions.question}</span></h3>
   </div>
   <div className={`toggle-inner ${this.state.questionActive ? 'active' : ''}`}
     dangerouslySetInnerHTML={{
       __html:questions.answer.childMarkdownRemark.html,
     }}
   />
  </div>
))}

The class Active is added by setting the state in the component as

constructor(props) {
  super(props);
  this.state = {
    questionActive: false
  }
  this.handleToggleActive = this.handleToggleActive.bind(this)
}

handleToggleActive() {
  this.setState({
    questionActive: !this.state.questionActive
  })
}

Upvotes: 0

Views: 243

Answers (1)

Liam
Liam

Reputation: 6743

Actually, there are many ways to do this here's one of them.

Pass the clicked id to the state then compear it in map id.

onClick={this.handleToggleActive.bind(this, questions)} 

I prefer you always to use arrow function to setState

handleToggleActive = (questions) => {
  this.setState({
    questionActive: questions.id
  })
}

Compear the state with current id in map

className={`toggle-title ${questions.id === this.state.questionActive ? 'active' : ''}`}

No need to bind handleToggleActive in constructor

I did an example

Edit 8xp0xjqow2

Upvotes: 1

Related Questions