learnyoureact icon indicating copy to clipboard operation
learnyoureact copied to clipboard

using v0.11.1 - handleChange called with incorrect context

Open joebartels opened this issue 9 years ago • 1 comments

https://github.com/kohei-takata/learnyoureact/blob/master/exercises/state/solution/views/index.jsx#L45

When handleChange is invoked after selecting checkbox, this is undefined and so this.setState throws error 'cannot call setState on undefined'. However when I bind this to handleChange in the onChange attribute it works. Any thoughts on why I have to do this:

<input
  type="checkbox"
  checked={this.state.checked}
  onChange={this.handleChange.bind(this)}
/>

rest of my Todo component:

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

   handleChange(e) {
     debugger;
     this.setState({ checked: e.target.checked });
   }
}

joebartels avatar Feb 07 '16 19:02 joebartels

http://reactkungfu.com/2015/07/why-and-how-to-bind-methods-in-your-react-component-classes/

According to some info from this blog post ^ the examples need to be updated for es6 classes. A few examples are given in blog for getting the intended context however the post is several months old and so wondering if a preferred pattern has emerged since?

I personally like the class properties pattern but then babel-plugin-syntax-class-properties needs to be included. And if you're just learning React you may easily take the example for granted and not realize the importance of context when it comes to event handlers...

class Todo extends React.Component{
  change = (ev) => this.setState({ text: ev.target.value });
}

joebartels avatar Feb 07 '16 20:02 joebartels