Skip to content

Instantly share code, notes, and snippets.

@jwill9999
Last active February 26, 2017 01:29
Show Gist options
  • Save jwill9999/1687e3dc6c0a4e876df74f5903e56fbf to your computer and use it in GitHub Desktop.
Save jwill9999/1687e3dc6c0a4e876df74f5903e56fbf to your computer and use it in GitHub Desktop.
React Events
/* preventing default behaviour */
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
/* with bind and this */
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')
);
/* with ES6 arrow functions */
class LoggingButton extends React.Component {
handleClick() {
console.log('this is:', this);
}
render() {
// This syntax ensures `this` is bound within handleClick
return (
<button onClick={(e) => this.handleClick(e)}>
Click me
</button>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment