Last active
February 26, 2017 01:29
-
-
Save jwill9999/1687e3dc6c0a4e876df74f5903e56fbf to your computer and use it in GitHub Desktop.
React Events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* preventing default behaviour */ | |
function ActionLink() { | |
function handleClick(e) { | |
e.preventDefault(); | |
console.log('The link was clicked.'); | |
} | |
return ( | |
<a href="#" onClick={handleClick}> | |
Click me | |
</a> | |
); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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') | |
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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