Skip to content

Instantly share code, notes, and snippets.

@shsunmoonlee
Created October 18, 2018 07:55
Show Gist options
  • Select an option

  • Save shsunmoonlee/bc9b608e773b66832ab2adee7ce674d3 to your computer and use it in GitHub Desktop.

Select an option

Save shsunmoonlee/bc9b608e773b66832ab2adee7ce674d3 to your computer and use it in GitHub Desktop.
React bind example
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment