Alberto Manuguerra
Alberto Manuguerra

Reputation: 149

array declaration in this.state React

**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]);        
      }
    );
}

Upvotes: 0

Views: 47

Answers (3)

bilwit
bilwit

Reputation: 819

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]
  }
)

Upvotes: 0

GalAbra
GalAbra

Reputation: 5138

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,
});

Upvotes: 2

Agney
Agney

Reputation: 19224

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

Upvotes: 1

Related Questions