Error changing state checkbox in Reactjs

Asked

Viewed 774 times

2

I’m still learning React in the state part of a component. My activity is simple: by clicking the checkbox the state of the CHECKED component should change to true and change the value of a text message. The problem is that by clicking I get the following error on the console: TypeError: this is undefined and nothing more.

My code used follows below:

class CheckBox extends React.Component{
    constructor(props){
      super(props);
      this.state = {checked: false};
    }

    changeState(){
      this.setState({
        checked : !this.state.checked
      });
    }

    render(){
      var msg;
      msg = this.state.checked ? 'Sim' : 'Não';
      return(
        <div>
          <input type="checkbox" defaultChecked={this.state.checked} onChange={this.changeState}/>
          <p>{msg}</p>
        </div>
      )
    }
  }

  ReactDOM.render(<CheckBox/>, document.getElementById('app'));

Could a wizard show me the way? Thank you very much.

1 answer

2


You need to indicate what the context is for changeState(), so he says that this is undefined.

Solution

onChange={this.changeState.bind(this)}

The bind(this) is passing the Component Checkbox to the context of changeState(), that way he can manipulate the state.


Poc

Another way is to connect the scope in the constructor, thus:

constructor(props){
  super(props);
  this.state = {checked: false};

  this.changeState = this.changeState.bind(this); // <--
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.