Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

using v0.11.1 - handleChange called with incorrect context #94

Open
joebartels opened this issue Feb 7, 2016 · 1 comment
Open

using v0.11.1 - handleChange called with incorrect context #94

joebartels opened this issue Feb 7, 2016 · 1 comment

Comments

@joebartels
Copy link

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
Copy link
Author

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 });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant