Search code examples
arraysreactjsreact-component

Modifying an array inside the state of a React Component


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?


Solution

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