React lets you add event handlers to your JSX. Event handlers are your own functions that will be triggered in response to interactions like clicking, hovering, focusing form inputs, and so on.
To add an event handler, you will first define a function and then pass it as a prop to the appropriate JSX tag. For example, here is a button that doesn’t do anything yet:
export default function Button() { return ( <button> I don't do anything </button> ); }
You can make it show a message when a user clicks by following these three steps:
handleClick
inside your Button
component.alert
to show the message).onClick={handleClick}
to the <button>
JSX.export default function Button() { function handleClick() { alert('You clicked me!'); } return ( <button onClick={handleClick}> Click me </button> ); }
You defined the handleClick
function and then passed it as a prop to <button>
. handleClick
is an event handler. Event handler functions:
handle
, followed by the name of the event.By convention, it is common to name event handlers as handle
followed by the event name. You’ll often see onClick={handleClick}
, onMouseEnter={handleMouseEnter}
, and so on.
Alternatively, you can define an event handler inline in the JSX:
<button onClick={function handleClick() { alert('You clicked me!'); }}>
Or, more concisely, using an arrow function:
<button onClick={() => { alert('You clicked me!'); }}>
All of these styles are equivalent. Inline event handlers are convenient for short functions.