Jan Peeter
Jan Peeter

Reputation: 357

update state for only one item in react

I am showing and hiding description on an item which is managed through state. The only problem is I am managing this state for all mapped items on my page which means the state will apply to all items. How can I only manage it for one item inside wrapped items?

Here is example of what I have done.

Here I set the state to not show the description:

this.state = {
        show: false
    }

On click it will show the description, which I did like this:

<div className="mx-auto pb-3">
    {this.state.show ? <div><p className="mb-6 pt-3 text-center">
        {node.description.description}
    </p></div> : null}
</div>

As mentioned above this applies to all mapped items which is wrapped like this:

 <div className="row mx-auto">
 {this.state.allProducts.map(({ node }) => {
....
 })}
</div>

And here is my onClick function

<div className="mx-auto">
    <p className="prd-desc-option" onClick={() => { this.setState({ show: 
    !this.state.show }) }}>{this.state.show ? 'Hide' : 'Show'} Description
    </p>
</div>

Upvotes: 1

Views: 220

Answers (1)

Striped
Striped

Reputation: 2547

You should manage the show attribute on the allProducts level and then based you condition on it:

<div className="row mx-auto">
  {this.state.allProducts.map(({ node }) => {
    <div className="mx-auto pb-3">
    {node.show ? 
      <div><p className="mb-6 pt-3 text-center">
        {node.description.description}
      </p></div> : null}
    </div>
  })}
</div>

Upvotes: 1

Related Questions