0

**I'm trying to create an array with 5 values which I could use with nameArray[number]. I think that the declaration of the array is wrong but I don't know how I can fix it. My idea is that: I have 5 buttons, when I click one of this, only one value of the 5 values in the state array change from false to true. **

constructor(props) {
    super(props);
    this.state = {
      activeButtons: [false, false, false, false, false]
    };
  }

  cliccato = (e) => {
    e.preventDefault();
    const number = parseInt(e.target.id);

    this.setState(
      {
        activeButtons: !this.state.activeButtons[number],
      },
      () => {
        console.log(" "+ this.state.activeButtons[number]);        
      }
    );
}
1
  • What exactly is the error in your code? Commented Apr 17, 2020 at 16:36

3 Answers 3

2

You're updating your state's activeButtons with a single boolean value, rather than an updated array.

You need to generate a new array and modify only the relevant element:

const newArray = [...this.state.activeButtons];
newArray[number] = !newArray[number];

this.setState({
  activeButtons: newArray,
});

Sign up to request clarification or add additional context in comments.

Comments

1

Declaration of the array is fine. You can make it shorter with Array(5).fill(false).

It's setting state part that needs work. In your current code, you are setting the state to the alternate of a boolean value, instead you need to set it to an array.

this.setState(prevState => ({
  activeButtons: prevState.activeButtons.map((val, index) => {
    if(index === number) {
      return !val;
    }
    return val;
  })
}));

Also, using the functional set state form here

Comments

0

It's because you're overwriting activeButtons every time with only one element value. You need to preserve the other values each time you want to update an element.

Using an Object would be a more graceful data structure in this case though.

this.setState(
  {
    activeButtons: {
        ...this.state.activeButtons
        [number]: !this.state.activeButtons[number]
  }
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.