Error changing checkbox state in Reactjs

2

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

My code used below follows:

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 any wizard tell me the way? Thank you in advance.

    
asked by anonymous 01.02.2018 / 15:29

1 answer

2

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

Solution

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

The bind(this) is passing the CheckBox component to the context of changeState() , so it can handle the state.

PoC

Another way is to link the scope in the constructor, like this:

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

  this.changeState = this.changeState.bind(this); // <--
}
    
01.02.2018 / 15:57