Sub topic 1
Attaching event handlers to elements
This chapter covers how to attach an event handler to an element in a React function component. It also covers the mistakes that most often break handlers. Later chapters cover the event object, handler arguments, and propagation in detail, so they only appear here where needed.
Prerequisites
This chapter assumes you already know the following:
- JavaScript functions and arrow functions, including how a function can be stored in a variable and passed around.
- Basic JSX syntax, including embedding JavaScript expressions in curly braces.
- Components and props in React.
- The basics of the
useStatehook.
If any of these are unfamiliar, review them first. Everything below builds on the idea that a function is a value you can pass to a prop.
What an event handler is
An event handler is a function that runs in response to something the user does, such as a click, a key press, or a form submission. In React you attach a handler by passing a function to a special prop on a built-in element. These props are named onClick, onChange, onSubmit, onKeyDown, and so on. They use camelCase, unlike the lowercase onclick attribute in plain HTML.
function SaveButton() {
function handleClick() {
alert('Saved');
}
return <button onClick={handleClick}>Save</button>;
}This component defines handleClick inside its body and passes it to onClick. When the user clicks the button, React calls handleClick. The function does not run while the component renders.
Two conventions are worth following from the start:
- Name the handler function with a
handleprefix followed by the event, such ashandleClickorhandleSubmit. - Define the handler inside the component, so that it can read the component's props and state.
Pass the function, do not call it
The most common beginner mistake is to call the function inside the JSX instead of passing it. Compare these two lines:
<button onClick={handleClick}>Save</button>
<button onClick={handleClick()}>Save</button>The first line passes a reference to the function. React stores it and calls it later, when a click happens. The second line calls handleClick immediately, while the component renders. It then passes the return value, usually undefined, to onClick. The handler fires on every render and never on a click.
If the handler also sets state, calling it during render causes an infinite loop. React reports an error such as "Too many re-renders".
Inline handlers
For short logic, you can write the function directly in the prop. An arrow function is the usual choice:
function Greeting() {
return (
<button onClick={() => alert('Hello')}>
Greet
</button>
);
}The value passed to onClick is the arrow function () => alert('Hello'). It is a function, so React can call it on click. This is the same pattern as the first example, with the function written in place.
The same trap applies here in a different form. This version is wrong:
<button onClick={alert('Hello')}>Greet</button>It calls alert during render and passes its return value. Wrap the call in () => to turn it into a function that runs later.
Choosing between named and inline handlers
| Style | Good for | Drawback |
|---|---|---|
| Named function (`handleClick`) | Handlers with several lines, or handlers reused by more than one element | Needs a separate declaration |
| Inline arrow function | One-line handlers, or passing an argument such as an item id | Becomes hard to read as it grows |
A common rule is to switch to a named function once the inline body needs more than one short statement. Creating a new inline function on every render is cheap and rarely a performance concern. You do not need to avoid it unless profiling shows a problem.
The handler receives an event object
React calls your handler with one argument, the event object. It describes what happened: which element was clicked, which key was pressed, and so on. You can ignore it when you do not need it, as the earlier examples do. If you do need it, declare a parameter:
function ClickLogger() {
function handleClick(event) {
console.log(event.type);
}
return <button onClick={handleClick}>Log</button>;
}Here event.type is "click". The next chapter looks at the event object in detail. For now, remember that React supplies it automatically. You do not pass it yourself when you give React a function reference.
Handlers see the state from the render that created them
A handler is an ordinary function defined during a render. It can read the props and state values from that render. This is called a closure, which means the function keeps access to the variables around it.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return <button onClick={handleClick}>Count: {count}</button>;
}On the first render, count is 0, so this render's handleClick calls setCount(0 + 1). After the click, React renders again with count equal to 1. That render creates a new handleClick that sees 1.
A handler does not see a state change made by its own setCount call. Reading count right after setCount(count + 1) still gives the old value. State updates have their own chapter later in this tutorial. Functional updates such as setCount(c => c + 1) avoid problems when the same handler updates state more than once.
Which props are available
React supports handler props for most browser events on built-in elements. Some common ones:
| Prop | Fires when |
|---|---|
| `onClick` | The user clicks the element |
| `onChange` | The value of a form field changes |
| `onSubmit` | A form is submitted |
| `onKeyDown` | A key is pressed while the element has focus |
| `onFocus` and `onBlur` | The element gains or loses focus |
| `onMouseEnter` and `onMouseLeave` | The pointer enters or leaves the element |
Handler props work on built-in elements such as <button>, <input>, and <form>. They do not work automatically on your own components. Writing <Button onClick={handleClick} /> only passes a prop named onClick to Button. The Button component must pass that prop on to a real <button> element before anything happens. A later chapter on passing handlers between components covers this.
Common errors
The following problems cause most "my handler does nothing" reports:
- Calling instead of passing.
onClick={handleClick()}runs the function during render. UseonClick={handleClick}oronClick={() => handleClick()}. - Wrong casing.
onclickandonClickare different. React only recognizes the camelCase prop names. Lowercase names on built-in elements are not treated as React event props. - Passing a string.
onClick="handleClick()"is HTML syntax. React expects a function, not a string. - Handler on a custom component.
<Card onClick={...} />does nothing unlessCardforwards the prop to an element. - Misspelled handler name. Referencing an undefined function causes a
ReferenceErrorwhen the component renders. Reading an undefined prop value instead gives a handler that never runs. - Disabled elements. A
<button disabled>does not fire click events. If a handler never runs, check for adisabledattribute.
A worked example
This component combines the pieces from the chapter. It has a named handler, an inline handler, and state.
import { useState } from 'react';
function LikeButton() {
const [likes, setLikes] = useState(0);
function handleLike() {
setLikes(likes + 1);
}
return (
<div>
<button onClick={handleLike}>Like ({likes})</button>
<button onClick={() => setLikes(0)}>Reset</button>
</div>
);
}
export default LikeButton;The first button uses the named function handleLike, because it reads the current count. The second uses an inline arrow function, because resetting is a single call. Both pass a function to onClick, and neither calls anything during render.
Summary of the key points
- Attach a handler by passing a function to a camelCase prop such as
onClick. - Pass the function itself. Do not call it in the JSX.
- Use an inline arrow function for short logic, and a named
handle...function for longer logic. - React calls the handler with an event object as its only argument.
- Handler props work on built-in elements. A custom component must forward them.
Exercise
A developer writes <button onClick={deleteItem(id)}>Delete</button> and finds the item deleted as soon as the page loads. What is wrong, and how do you fix it?
Show answer
The expression deleteItem(id) calls the function during render and passes its return value to onClick. Wrap the call in an arrow function so that React receives a function to call later: <button onClick={() => deleteItem(id)}>Delete</button>.
Exercise
You write <Card onClick={handleSelect} />, but clicking the card does nothing. The Card component renders <div className="card">{children}</div>. Why, and what change makes the click work?
Show answer
onClick on a custom component is only a prop named onClick. React does not attach it to any DOM element. Change Card to accept the prop and pass it to the div, for example function Card({ onClick, children }) { return <div className="card" onClick={onClick}>{children}</div>; }.
Exercise
In the Counter example, handleClick calls setCount(count + 1). Why does count still hold the old value if you log it on the next line inside handleClick?
Show answer
The handler is a closure over the count from the render that created it. That value is fixed for the render. setCount schedules a new render, and only that new render sees the updated value.