0

In React Docs, handling events article: how state is being updated to the opposite boolean value, I have a question.

Why do we need to add .isToggleOn after isToggleOn: !prevState

Why can't I just simply write isToggleOn: !prevState?

prevState is {isToggleOn: true}. So !prevState should be {isToggleOn: false}. Am I right? It confuses me, because it sounds like {property: opposite of the boolean.property}.

I know what prevState is and I know .setState() is updating the state. Please help me better understand this. Thank you so much in advance!

 class Toggle extends React.Component {
      constructor(props) {
        super(props);
        this.state = {isToggleOn: true};
    
        // This binding is necessary to make `this` work in the callback
        this.handleClick = this.handleClick.bind(this);
      }
    
      handleClick() {
        this.setState(prevState => ({
          isToggleOn: !prevState.isToggleOn
        }));
      }
    
      render() {
        return (
          <button onClick={this.handleClick}>
            {this.state.isToggleOn ? 'ON' : 'OFF'}
          </button>
        );
      }
    }
    
    ReactDOM.render(
      <Toggle />,
      document.getElementById('root')
    );
J L
  • 13
  • 2
  • Welcome to SO. JavaScript does not work as you've mentioned. If `prevState` is `{isToggleOn: true}` then `!prevState` is just `false`. If `prevState` is `{isToggleOn: false}` then `!prevState` is also `false`. You can try it in browser console. `!` operator [converts](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT) the whole object to Boolean before applying `not` to it – Vitalii Jul 06 '21 at 23:50

2 Answers2

1

prevState is an object, so you cannot change the properties inside it by using "!" on the whole object. What you need is to change a value within this object, which has key "isToggleOn". Thereby, by using

this.setState(prevState => ({
  isToggleOn: !prevState.isToggleOn
}));

you access this value by key "isToggleOn" and change it to the opposite

alexnik42
  • 188
  • 10
0

In react, the state object is a collection of values, not just a single value. In order to update a specific piece of your state, you need to pass the key of that specific state value in order for it to know what to change.

For example, your state value could be something like this:

this.state = {
  isToggleOn: true,
  otherValue: false
}

And when you're updating, only the value for the specific key you pass is updated. So if you were to run

this.setState(prevState => ({
  isToggleOn: !prevState.isToggleOn
}));

only the isToggleOn value would change and the otherValue field would remain as false.

Chris Sandvik
  • 1,787
  • 9
  • 19