--- title: 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 {/*adding-event-handlers*/} To add an event handler, you will first define a function and then [pass it as a prop](/learn/passing-props-to-a-component) to the appropriate JSX tag. For example, here is a button that doesn't do anything yet: ```js export default function Button() { return ( ); } ``` You can make it show a message when a user clicks by following these three steps: 1. Declare a function called `handleClick` *inside* your `Button` component. 2. Implement the logic inside that function (use `alert` to show the message). 3. Add `onClick={handleClick}` to the ` ); } ``` ```css button { margin-right: 10px; } ``` You defined the `handleClick` function and then [passed it as a prop](/learn/passing-props-to-a-component) to ` ); } export default function Toolbar() { return (
Play Movie Upload Image
); } ``` ```css button { margin-right: 10px; } ``` This lets these two buttons show different messages. Try changing the messages passed to them. ### Passing event handlers as props {/*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: ```js function Button({ onClick, children }) { return ( ); } function PlayButton({ movieName }) { function handlePlayClick() { alert(`Playing ${movieName}!`); } return ( ); } function UploadButton() { return ( ); } export default function Toolbar() { return (
); } ``` ```css button { margin-right: 10px; } ```
Here, the `Toolbar` component renders a `PlayButton` and an `UploadButton`: - `PlayButton` passes `handlePlayClick` as the `onClick` prop to the `Button` inside. - `UploadButton` passes `() => alert('Uploading!')` as the `onClick` prop to the `Button` inside. Finally, your `Button` component accepts a prop called `onClick`. It passes that prop directly to the built-in browser ` ); } export default function App() { return (
); } ``` ```css button { margin-right: 10px; } ``` In this example, ` ); } function Button({ onClick, children }) { return ( ); } ``` ```css 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 `Button`s, 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. Make sure that you use the appropriate HTML tags for your event handlers. For example, to handle clicks, use [` ); } ``` ```css .Toolbar { background: #aaa; padding: 5px; } button { margin: 5px; } ``` If you click on either button, its `onClick` will run first, followed by the parent `
`'s `onClick`. So two messages will appear. If you click the toolbar itself, only the parent `
`'s `onClick` will run. All events propagate in React except `onScroll`, which only works on the JSX tag you attach it to. ### Stopping propagation {/*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. That event object also lets you stop the propagation. If you want to prevent an event from reaching parent components, you need to call `e.stopPropagation()` like this `Button` component does: ```js function Button({ onClick, children }) { return ( ); } export default function Toolbar() { return (
{ alert('You clicked on the toolbar!'); }}>
); } ``` ```css .Toolbar { background: #aaa; padding: 5px; } button { margin: 5px; } ```
When you click on a button: 1. React calls the `onClick` handler passed to `
``` Each event propagates in three phases: 1. It travels down, calling all `onClickCapture` handlers. 2. It runs the clicked element's `onClick` handler. 3. It travels upwards, calling all `onClick` handlers. Capture events are useful for code like routers or analytics, but you probably won't use them in app code. ### Passing handlers as alternative to propagation {/*passing-handlers-as-alternative-to-propagation*/} Notice how this click handler runs a line of code _and then_ calls the `onClick` prop passed by the parent: ```js {4,5} function Button({ onClick, children }) { return ( ); } ``` You could add more code to this handler before calling the parent `onClick` event handler, too. This pattern provides an *alternative* to propagation. It lets the child component handle the event, while also letting the parent component specify some additional behavior. Unlike propagation, it's not automatic. But the benefit of this pattern is that you can clearly follow the whole chain of code that executes as a result of some event. If you rely on propagation and it's difficult to trace which handlers execute and why, try this approach instead. ### Preventing default behavior {/*preventing-default-behavior*/} Some browser events have default behavior associated with them. For example, a `
` submit event, which happens when a button inside of it is clicked, will reload the whole page by default: ```js export default function Signup() { return ( alert('Submitting!')}> ); } ``` ```css button { margin-left: 5px; } ```
You can call `e.preventDefault()` on the event object to stop this from happening: ```js export default function Signup() { return (
{ e.preventDefault(); alert('Submitting!'); }}>
); } ``` ```css button { margin-left: 5px; } ```
Don't confuse `e.stopPropagation()` and `e.preventDefault()`. They are both useful, but are unrelated: * [`e.stopPropagation()`](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) stops the event handlers attached to the tags above from firing. * [`e.preventDefault()` ](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) prevents the default browser behavior for the few events that have it. ## Can event handlers have side effects? {/*can-event-handlers-have-side-effects*/} Absolutely! Event handlers are the best place for side effects. Unlike rendering functions, event handlers don't need to be [pure](/learn/keeping-components-pure), so it's a great place to *change* something—for example, change an input's value in response to typing, or change a list in response to a button press. However, in order to change some information, you first need some way to store it. In React, this is done by using [state, a component's memory.](/learn/state-a-components-memory) You will learn all about it on the next page. * You can handle events by passing a function as a prop to an element like ` ); } ``` The problem is that ` ); } ``` Alternatively, you could wrap the call into another function, like ` ); } ``` #### Wire up the events {/*wire-up-the-events*/} This `ColorSwitch` component renders a button. It's supposed to change the page color. Wire it up to the `onChangeColor` event handler prop it receives from the parent so that clicking the button changes the color. After you do this, notice that clicking the button also increments the page click counter. Your colleague who wrote the parent component insists that `onChangeColor` does not increment any counters. What else might be happening? Fix it so that clicking the button *only* changes the color, and does _not_ increment the counter. ```js src/ColorSwitch.js active export default function ColorSwitch({ onChangeColor }) { return ( ); } ``` ```js src/App.js hidden import { useState } from 'react'; import ColorSwitch from './ColorSwitch.js'; export default function App() { const [clicks, setClicks] = useState(0); function handleClickOutside() { setClicks(c => c + 1); } function getRandomLightColor() { let r = 150 + Math.round(100 * Math.random()); let g = 150 + Math.round(100 * Math.random()); let b = 150 + Math.round(100 * Math.random()); return `rgb(${r}, ${g}, ${b})`; } function handleChangeColor() { let bodyStyle = document.body.style; bodyStyle.backgroundColor = getRandomLightColor(); } return (


Clicks on the page: {clicks}

); } ```
First, you need to add the event handler, like ` ); } ``` ```js src/App.js hidden import { useState } from 'react'; import ColorSwitch from './ColorSwitch.js'; export default function App() { const [clicks, setClicks] = useState(0); function handleClickOutside() { setClicks(c => c + 1); } function getRandomLightColor() { let r = 150 + Math.round(100 * Math.random()); let g = 150 + Math.round(100 * Math.random()); let b = 150 + Math.round(100 * Math.random()); return `rgb(${r}, ${g}, ${b})`; } function handleChangeColor() { let bodyStyle = document.body.style; bodyStyle.backgroundColor = getRandomLightColor(); } return (


Clicks on the page: {clicks}

); } ```
--- ## Sitemap [Overview of all docs pages](/llms.txt)