Handling Events in React
Making your React applications interactive.
Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences:
- React events are named using camelCase, rather than lowercase (e.g., `onClick` instead of `onclick`).
- With JSX you pass a function as the event handler, rather than a string.
For example, the HTML:
<button onclick="activateLasers()">Activate Lasers</button>
is slightly different in React:
<button onClick={activateLasers}>Activate Lasers</button>Another difference is that you cannot return `false` to prevent default behavior in React. You must call `event.preventDefault()` explicitly.
Test Your Knowledge
How do you handle an `onClick` event in a React button?
What is the purpose of `event.preventDefault()` in an event handler?
In React, event handlers are typically passed as:
What is `event.stopPropagation()` used for?