javascript – Update array in React

Question:

Having the following code,

this.state = { 
        valores: ['A', 'B', 'C']
}

How could I update an element of this array? Of the kind:

this.setState({
    valores[1]: 'a'
})

Answer:

I recommend not directly mutating the state object, instead assigning it to a variable and reassigning it.

Here you can read some reasons why you should not mutate directly https://daveceddia.com/why-not-modify-react-state-directly/

You could also use https://github.com/kolodny/immutability-helper

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this)
    this.state = {
      valores: ['a', 'b', 'c']
    };
  }
  
 handleClick(e) {
    e.preventDefault();
    var valores = this.state.valores;
    valores[0] = Math.random();
    this.setState({valores: valores});
  }
 
  render() {
    return (
      <div>
        <div>{this.state.valores}</div>
        <button onClick={this.handleClick}>Cambiar primer valor</button>
      </div>
    );
  }
};

ReactDOM.render(
  <MyComponent />,
  document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Scroll to Top