When handling events inside React elements, there are two very important differences from the way we do so with the DOM API:
- All React elements attributes (events included) are named using camelCase, rather than lowercase. It’s
onClick, notonclick. - We pass an actual JavaScript function reference as the event handler, rather than a string. It’s
onClick={handleClick}, notonClick="handleClick".
React wraps the DOM event object with an object of its own to optimize the performance of events handling. But inside an event handler, we can still access all methods available on the DOM event object. React passes that wrapped event object to every handle call. For example, to prevent a form from the default submission action, you can do:
// Example 12 - Working with wrapped events
// https://jscomplete.com/repl?j=HkIhRoKBb
class Form extends React.Component {
handleSubmit = (event) => {
event.preventDefault();
console.log('Form submitted');
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
}
// Use it
ReactDOM.render(<Form />, mountNode);