0

I have an array inside the state of a React Component. I want to update a specific (in my case, topmost) element of the array using setState. How can I do this?

Jithin Ks
  • 479
  • 2
  • 9
  • 18

2 Answers2

1

If you will need an explanation, I will update my answer :)

class MyComponent extens React.Component {
    state = {
        myAwesomeArray: [1, 2, 3]
    }

    changeArray() {
        var myAwesomeArray = [...this.state.myAwesomeArray]
        myAwesomeArray[0] = -1
        this.setState({ myAwesomeArray })
    }

    render() {
        return (
            <div>
                {this.state.myAwesomeArray.map(el => <p key={p}>{el}</p>)}
                <button onClick={this.changeArray}>Change my array!</button>
            </div>
        )
    }
}
Limbo
  • 2,123
  • 21
  • 41
0

You can do like this

 const rawRequestData = this.state.data;
    rawRequestData[index].key = "Custom key";
    this.setState({ data: rawRequestData });

and If you would like to use third party lib the try with this lib, I used some function of this and got excellent result.

https://github.com/kolodny/immutability-helper

Limbo
  • 2,123
  • 21
  • 41
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29