Skip to content

Instantly share code, notes, and snippets.

@mckennatim
Created December 26, 2016 20:54
Show Gist options
  • Save mckennatim/0d6f4ce5e59d7d04a6612966b5021cf5 to your computer and use it in GitHub Desktop.
Save mckennatim/0d6f4ce5e59d7d04a6612966b5021cf5 to your computer and use it in GitHub Desktop.
Toggle
<div id="root">
</div>
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(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script>
body {
padding: 5px
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment