A button that's clicked, a field that's typed in, a form that's sent: these are all events (things that happen on the page). A page only feels alive when it reacts to events. In React, that reaction is written as an event handler: a function React runs when the event happens. You don't run it yourself. You only hand it to the element.
It's like leaving a message with the building guard: "When my parcel arrives, please call me." You hand over the instruction, and the guard follows it later, when the parcel arrives. If you make the phone call yourself right then instead, all you leave with the guard is the result: nothing. When the parcel comes, nothing happens. In React, the guard is React, the instruction is the handler function, and the parcel arriving is the event, such as a click. Making the phone call right then is calling the handler yourself.
Attach a handler with onClick
This component shows a button that prints a greeting to the console:
function App() {
const handleClick = () => {
console.log("Hello!");
};
return (
<button id="greet" onClick={handleClick}>
Greet
</button>
);
}
handleClickis an ordinary function. Thehandle...name is just a habit that makes it easy to spot.onClick={handleClick}hands that function to the button. React calls it every time the button is clicked.- Event names in React are written in camelCase (the second word and every word after it start with a capital letter):
onClick,onChange,onSubmit, notonclickas in HTML. The value is a function inside{ }, not code written as text in quotes.
Click the Greet button 2 times and the console holds 2 lines of Hello!.
Pass the function, don't call it
The only difference is (), but the meaning is very different:
| Written as | What onClick receives |
When handleClick runs |
|---|---|---|
onClick={handleClick} |
the function handleClick |
every time the button is clicked |
onClick={handleClick()} |
the result of calling it: undefined |
when the component renders, not when it's clicked |
With (), handleClick runs right away, while React runs the component (the render). This has two results:
- "Hello!" is printed once on every render, not on every click.
onClickonly receivesundefined(the result of that call), so a click does nothing.
It gets worse when the handler changes data that makes React run the component again. That kind of data is called state, and the next lesson covers it. The order is: render, call the handler, change the state, render again, call the handler again, over and over. In the end React stops with the error Too many re-renders.
Pass an argument: wrap it in an arrow function
Sometimes a handler needs data. For example, handleDelete needs the id of the item to delete. onClick={handleDelete(id)} is wrong, because the () calls the function right away, during the render. Wrap it in an arrow function:
<button onClick={() => handleDelete(id)}>Delete</button>
() => handleDelete(id) is a new function that hasn't run yet. React keeps it. Only when the button is clicked does that new function call handleDelete(id).
The event object and e.target.value
React calls a handler with one argument: the event object, usually named e. The event object describes what happened:
e.target: the element where the event happened.e.target.value: what's in the input field right now.
This component shows whatever is typed in the input field:
function App() {
const [text, setText] = useState("");
return (
<div>
<input id="name" onChange={(e) => setText(e.target.value)} />
<p id="output">{text}</p>
</div>
);
}
useState("")sets up a place to keep a value that shows on the page.textis the value (empty at first).setText(newValue)replaces it, and then React runs the component again (a re-render) with the new value. The full story is in the next lesson, useState.onChangein React runs on every keystroke. Thechangeevent in plain HTML is different: it only runs when you leave the field.- Type
B,u,d,i: the handler runs 4 times, and<p id="output">readsB,Bu,Bud,Budiin turn.
e.preventDefault(): cancel the browser's built-in action
Some elements have a built-in action (something the browser does without any code from you). When a form is sent, the browser reloads the page (or goes to another page). A link takes you to a new address. Once the page reloads, everything on it is gone. e.preventDefault() cancels that built-in action, so you decide what happens:
function GreetForm() {
const handleSubmit = (e) => {
e.preventDefault();
console.log("Form sent!");
};
return (
<form onSubmit={handleSubmit}>
<input name="name" />
<button>Send</button>
</form>
);
}
A button inside a <form> sends that form when it's clicked. onSubmit goes on the <form>, not on its button, so the handler also runs when someone presses Enter in the input field.
⚠️ Handlers that don't run, or run at the wrong time
onClick={handleClick()}. The function runs during the render, not when the button is clicked. Remove the(), or wrap it in() => ...when you need an argument.- Lowercase
onclick. React doesn't recognise it. WriteonClick. - Forgetting the
eparameter.const handleChange = () => setText(e.target.value)fails because there's noe. Write(e) => .... - Forgetting
e.preventDefault()inonSubmit. The page reloads and everything is gone, console logs included.
TL;DR: An event handler is a function React runs when an event (such as a click or a keystroke) happens. You hand it to an element through a prop whose name is written in camelCase: onClick, onChange, onSubmit. Pass the function, don't call it: write onClick={handleClick}, not onClick={handleClick()}. The version with () runs during render (while React runs the component), and the click then does nothing. Need an argument? Write onClick={() => handleDelete(id)}. A handler receives the event object e, which describes what happened. e.target.value is what's in an input (in React onChange runs on every keystroke). e.preventDefault() cancels the browser's built-in action, such as reloading the page when a form is sent.
⚡ Hand a function to onClick
Write:
function App() {
const handleClick = () => {
console.log("Hello!");
};
return (
<button id="greet" onClick={handleClick}>
Greet
</button>
);
}
Meaning: An event is something that happens, such as a click. A function that React runs when an event happens is called an event handler. onClick={handleClick} hands the function handleClick to the button, and React calls it every time the button is clicked. Event names are written in camelCase: onClick, onChange, onSubmit.
⚡ Pass it, don't call it
Guess first: what's the difference between onClick={handleClick} and onClick={handleClick()}?
The second runs handleClick right away, while React runs the component (the render), and onClick only receives the result of that call, undefined. So a click does nothing.
Meaning: Need an argument, such as the id of the item to delete? Wrap the handler call in an arrow function: onClick={() => handleDelete(id)}. That arrow function calls handleDelete(id) only when the button is clicked.
⚡ What's typed is in e.target.value
Write:
<input id="name" onChange={(e) => setText(e.target.value)} />
<p id="output">{text}</p>
Meaning: React calls a handler with the event object e (a description of what happened), and e.target.value is what's in the input right now. In React, onChange runs on every keystroke. setText replaces the value text that shows in the <p>, and then React runs the component again. text and setText come from useState, which the next lesson covers.
⚡ Cancel the browser's built-in action
Meaning: When a form is sent, the browser reloads the page by itself (its built-in action), and everything on it is gone. e.preventDefault() in the onSubmit handler (which goes on the <form>) cancels that built-in action, so you decide what happens.