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?
Asked
Active
Viewed 979 times
2 Answers
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
-
Thanks very much.... :D. It worked!!! – Jithin Ks May 05 '18 at 12: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.

Limbo
- 2,123
- 21
- 41

Nishant Dixit
- 5,388
- 5
- 17
- 29