Chabou bou
Chabou bou

Reputation: 49

How can I change state of one element without affecting others with the same state?

So, I will try to make this quick, when I click on the div with the className "question" I want my icon to change from angle-up to angle-down and vice versa (also want to make another div visible / invisible). Things is, I'm currently using this.state.icon, so when I click on one question all the icon change for all the other too (same for the reveal things) Here is my code :

I'm on mobile so i make a pastebin

So, my question is, how can I change the icon and reveal the answer only for the question I click on ?

Thanks in advance for any help ! :)

Upvotes: 1

Views: 116

Answers (2)

Ben R.
Ben R.

Reputation: 2155

Blockquote "Things is, I'm currently using this.state.icon, so when I click on one question all the icon change for all the other too (same for the reveal things)"

The problem is that every question shares the same state. The block shown below should be extracted into its own component, and it should be in that component that the state is kept which determines whether to expand the question.

Then, in your parent container, you can just list multiple e.g. <Question /> components, and provide the text for each question/answer.

<div className={styles.category}>
    <h2>Cat</h2>
    <div className={styles.question}>
        <p>Question 1 ?<FontAwesomeIcon className={styles.iconAngle} icon={this.state.icon} /></p>
    </div>
    {
        this.state.showMe
        ? <div className={styles.answer}>
            <className={styles.titleAnswer}>Title 1</h3>
            <p>Answer 1 </p>
        </div>
        : null
    }
</div>

Upvotes: 1

prabin badyakar
prabin badyakar

Reputation: 1736

Not sure this is exactly what you are looking for but here is my solution

class CommissionData extends Component {
  constructor() {
    super();

    this.showUpArrow = false;
  }

  onUpdateArrow =()=> {
    this.showUpArrow = !this.showUpArrow
  }

  ...your code
}

In this way you can update your icon and div without using state

Upvotes: 0

Related Questions