Default Event Handler
you cannot return false to prevent default behavior in React. You must
call preventDefault
instead of
<form onsubmit="console.log('You clicked submit.'); return false"><button type="submit">Submit</button></form>
write
function Form() {
function handleSubmit(e) { e.preventDefault(); console.log('You clicked submit.'); }
return ( <form onSubmit={handleSubmit}><button type="submit">Submit</button></form> );
}
Event Handling in ES6 Class
in ES6 Class
When you define a component using an ES6 class, a common pattern is for an event handler to be a method on the class.
class Toggle extends React.Component {
constructor(props) {
super(props); this.state = {isToggleOn: true};
this.handleClick = this.handleClick.bind(this); // This binding is necessary to make `this` work in the callback
}
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') );
If you aren't using class fields syntax, you can use an arrow function
in the callback:
class LoggingButton extends React.Component {
handleClick() { console.log('this is:', this); }
render() {
// This syntax ensures `this` is bound within handleClick
return ( <button onClick={() => this.handleClick()}> Click me </button> );
}
}