Skip to content

Instantly share code, notes, and snippets.

@rBurgett
Created June 28, 2016 15:55
Show Gist options
  • Save rBurgett/b46aa39447fd8ea855a1938e17aefa29 to your computer and use it in GitHub Desktop.
Save rBurgett/b46aa39447fd8ea855a1938e17aefa29 to your computer and use it in GitHub Desktop.
// Example #1, this has a problem
class MyComponet extends React.Component {
constructor(props) {
super(props);
this.state = {
selected: false
}
}
itemClicked(e) {
e.preventDefault();
// Oops! We are about to get an error that we can't read property state of undefined
// this is because this is not bound to the context of the class. We need to manually
// bind it to make it work.
const currentState = this.state;
this.setState(Object.assign({}, currentState, {
seleted: !currentState.selected
}))
}
render() {
const { state } = this;
return (
<div>
<h1>{`Selected is ${state.selected}`}</h1>
<button type="button" onClick={this.itemClicked}>Click to select!</button>
</div>
);
}
}
// Example #2, this works
class MyComponet extends React.Component {
constructor(props) {
super(props);
this.state = {
selected: false
}
}
itemClicked(e) {
e.preventDefault();
// context is correctly bound now, so all works
const currentState = this.state;
this.setState(Object.assign({}, currentState, {
seleted: !currentState.selected
}))
}
render() {
return (
<div>
<h1>{`Selected is ${state.selected}`}</h1>
{/*
You have two options for correctly binding the method call.
One is with an arrow function which implicitly binds the method
to the current context of this.
*/}
<button type="button" onClick={e => this.itemClicked(e)}>Click to select!</button>
{/*
Another option is to explicitly bind the method using something like Lodash's _.bind()
*/}
<button type="button" onClick={_.bind(this.itemClicked, this)}>Click to select!</button>
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment