Responding to Events
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.
- Different ways to write an event handler
- How to pass event handling logic from a parent component
- How events propagate and how to stop them
Adding event handlers
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:
- Declare a function called
handleClickinside yourButtoncomponent. - Implement the logic inside that function (use
alertto show the message). - Add
onClick={handleClick}to the<button>JSX.
export default function Button() {
function handleClick() {
alert('You clicked me!');
}
return (
<button onClick={handleClick}>
Click me
</button>
);
}
button { margin-right: 10px; }
You defined the handleClick function and then passed it as a prop to <button>. handleClick is an event handler. Event handler functions:
- Are usually defined inside your components.
- Have names that start with
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.
[!WARNING]
Functions passed to event handlers must be passed, not called. For example:
passing a function (correct) calling a function (incorrect) <button onClick={handleClick}><button onClick={handleClick()}>The difference is subtle. In the first example, the
handleClickfunction is passed as anonClickevent handler. This tells React to remember it and only call your function when the user clicks the button.In the second example, the
()at the end ofhandleClick()fires the function immediately during rendering, without any clicks. This is because JavaScript inside the JSX{and}executes right away.When you write code inline, the same pitfall presents itself in a different way:
passing a function (correct) calling a function (incorrect) <button onClick={() => alert('...')}><button onClick={alert('...')}>Passing inline code like this won't fire on click—it fires every time the component renders:
// This alert fires when the component renders, not when clicked!
<button onClick={alert('You clicked me!')}>
If you want to define your event handler inline, wrap it in an anonymous function like so:
<button onClick={() => alert('You clicked me!')}>
Rather than executing the code inside with every render, this creates a function to be called later.
In both cases, what you want to pass is a function:
<button onClick={handleClick}>passes thehandleClickfunction.<button onClick={() => alert('...')}>passes the() => alert('...')function.
Reading props in event handlers
Because event handlers are declared inside of a component, they have access to the component's props. Here is a button that, when clicked, shows an alert with its message prop:
function AlertButton({ message, children }) {
return (
<button onClick={() => alert(message)}>
{children}
</button>
);
}
export default function Toolbar() {
return (
<div>
<AlertButton message="Playing!">
Play Movie
</AlertButton>
<AlertButton message="Uploading!">
Upload Image
</AlertButton>
</div>
);
}
button { margin-right: 10px; }
This lets these two buttons show different messages. Try changing the messages passed to them.
Passing event handlers as props
Often you'll want the parent component to specify a child's event handler. Consider buttons: depending on where you're using a Button component, you might want to execute a different function—perhaps one plays a movie and another uploads an image.
To do this, pass a prop the component receives from its parent as the event handler like so:
function Button({ onClick, children }) {
return (
<button onClick={onClick}>
{children}
</button>
);
}
function PlayButton({ movieName }) {
function handlePlayClick() {
alert(`Playing ${movieName}!`);
}
return (
<Button onClick={handlePlayClick}>
Play "{movieName}"
</Button>
);
}
function UploadButton() {
return (
<Button onClick={() => alert('Uploading!')}>
Upload Image
</Button>
);
}
export default function Toolbar() {
return (
<div>
<PlayButton movieName="Kiki's Delivery Service" />
<UploadButton />
</div>
);
}
button { margin-right: 10px; }
Here, the Toolbar component renders a PlayButton and an UploadButton:
PlayButtonpasseshandlePlayClickas theonClickprop to theButtoninside.UploadButtonpasses() => alert('Uploading!')as theonClickprop to theButtoninside.
Finally, your Button component accepts a prop called onClick. It passes that prop directly to the built-in browser <button> with onClick={onClick}. This tells React to call the passed function on click.
If you use a design system, it's common for components like buttons to contain styling but not specify behavior. Instead, components like PlayButton and UploadButton will pass event handlers down.
Naming event handler props
Built-in components like <button> and <div> only support browser event names like onClick. However, when you're building your own components, you can name their event handler props any way that you like.
By convention, event handler props should start with on, followed by a capital letter.
For example, the Button component's onClick prop could have been called onSmash:
function Button({ onSmash, children }) {
return (
<button onClick={onSmash}>
{children}
</button>
);
}
export default function App() {
return (
<div>
<Button onSmash={() => alert('Playing!')}>
Play Movie
</Button>
<Button onSmash={() => alert('Uploading!')}>
Upload Image
</Button>
</div>
);
}
button { margin-right: 10px; }
In this example, <button onClick={onSmash}> shows that the browser <button> (lowercase) still needs a prop called onClick, but the prop name received by your custom Button component is up to you!
When your component supports multiple interactions, you might name event handler props for app-specific concepts. For example, this Toolbar component receives onPlayMovie and onUploadImage event handlers:
export default function App() {
return (
<Toolbar
onPlayMovie={() => alert('Playing!')}
onUploadImage={() => alert('Uploading!')}
/>
);
}
function Toolbar({ onPlayMovie, onUploadImage }) {
return (
<div>
<Button onClick={onPlayMovie}>
Play Movie
</Button>
<Button onClick={onUploadImage}>
Upload Image
</Button>
</div>
);
}
function Button({ onClick, children }) {
return (
<button onClick={onClick}>
{children}
</button>
);
}
button { margin-right: 10px; }
Notice how the App component does not need to know what Toolbar will do with onPlayMovie or onUploadImage. That's an implementation detail of the Toolbar. Here, Toolbar passes them down as onClick handlers to its Buttons, but it could later also trigger them on a keyboard shortcut. Naming props after app-specific interactions like onPlayMovie gives you the flexibility to change how they're used later.
[!NOTE]
Make sure that you use the appropriate HTML tags for your event handlers. For example, to handle clicks, use
<button onClick={handleClick}>instead of<div onClick={handleClick}>. Using a real browser<button>enables built-in browser behaviors like keyboard navigation. If you don't like the default browser styling of a button and want to make it look more like a link or a different UI element, you can achieve it with CSS. Learn more about writing accessible markup.
Event propagation
Event handlers will also catch events from any children your component might have. We say that an event "bubbles" or "propagates" up the tree: it starts with where the event happened, and then goes up the tree.
This <div> contains two buttons. Both the <div> and each button have their own onClick handlers. Which handlers do you think will fire when you click a button?
export default function Toolbar() {
return (
<div className="Toolbar" onClick={() => {
alert('You clicked on the toolbar!');
}}>
<button onClick={() => alert('Playing!')}>
Play Movie
</button>
<button onClick={() => alert('Uploading!')}>
Upload Image
</button>
</div>
);
}
.Toolbar {
background: #aaa;
padding: 5px;
}
button { margin: 5px; }
If you click on either button, its onClick will run first, followed by the parent <div>'s onClick. So two messages will appear. If you click the toolbar itself, only the parent <div>'s onClick will run.
[!WARNING]
All events propagate in React except
onScroll, which only works on the JSX tag you attach it to.
Stopping propagation
Event handlers receive an event object as their only argument. By convention, it's usually called e, which stands for "event". You can use this object to read information about the event.
