Lesson 7
18 min
onClick, onChange, the event object and passing arguments to handlers.
Definition
An event is an action that occurs on a page, most often triggered by the user: a click, a key press, or a form submission. An event handleris the function you associate with that event to decide what should happen when it occurs. In React, you attach it directly to a JSX element using a camelCase attribute, such asonClick.
Thanks to state, you now know how to make the display change. But one piece is still missing: what triggers that change? The answer is events. They connect what the user does to your component's state. In this lesson, you will learn how to respond to a click, read what the user types, and pass information to your functions.
Lesson Objectives
onClick and other event attributes.An interface must respond when the user clicks, types on the keyboard, or submits a form. In React, you attachevent handlers directly in JSX using camelCase attributes:onClick,onChange,onSubmit,onMouseEnter, etc.
Each of these names corresponds to a specific type of event.onClickis triggered when an element is clicked,onChangewhen an input's value changes,onSubmitwhen a form is submitted, andonMouseEnterwhen the mouse pointer enters an element. The attribute's value is always a function: the one React will call at the right moment.
You do not need to know all of them right away. Here are the ones you will encounter most often, grouped by interaction type. They are all written in camelCase and begin withon.
onClick,onDoubleClick,onMouseEnter,onMouseLeave.onKeyDown(key pressed),onKeyUp(key released).onChange(value changes),onFocus(field receives focus),onBlur(field loses focus).onSubmit(form is submitted).An important note: in React,onChangeis triggered on every change to the value, meaning every time the user types in a text field. This differs from the native HTML event of the same name, which waits until the user leaves the field.
function Button() {
function sayHello() {
alert("Hello!");
}
return <button onClick={sayHello}>Say hello</button>;
}
export default Button;Here, we first define a function calledsayHelloinside the component, then pass it to the button'sonClickattribute. When the user clicks, React executes the function and the dialog box appears. As long as nobody clicks, the function simply remains "waiting": it is not executed.
Common Pitfall
You pass the function; you do notcall it. WriteonClick={sayHello}, notonClick={sayHello()}: with parentheses, the function would execute as soon as the page renders, not when the button is clicked.
The difference between passing and calling is the most common source of errors with events. The following code compares three forms you will encounter, along with the result of each.
function Comparison() {
function sayHello() {
alert("Hello!");
}
return (
<div>
{/* Correct: the function is passed and runs on click */}
<button onClick={sayHello}>A</button>
{/* Correct: arrow function, runs on click */}
<button onClick={() => sayHello()}>B</button>
{/* Incorrect: the function runs during rendering */}
<button onClick={sayHello()}>C</button>
</div>
);
}In case C, the parentheses call the function while React is building the page. The dialog box therefore appears immediately, before any click occurs, and whatonClickreceives is the result of the function (nothing in this case), not the function itself. Cases A and B produce the same behavior. Case B becomes essential when you need to pass an argument, as you will see later.
You can define your function separately with a name, or write it directly in the attribute. Both approaches work; the choice depends on the length of the code.
function Example() {
// Named handler: useful for multiple instructions
function showMessage() {
const hour = new Date().getHours();
alert("It is " + hour + " o'clock");
}
return (
<div>
<button onClick={showMessage}>What time is it?</button>
{/* Inline: useful for a very short action */}
<button onClick={() => alert("Thank you!")}>Say thanks</button>
</div>
);
}A simple rule: if the handler fits on one line, write it inline; if it requires several lines, give it a name. A named handler is easier to read, easier to test, and can be reused across several elements. By convention, these functions are named with the prefixhandleoronfollowed by the action, such ashandleClick.
Events become truly useful when they update state. Here is a "Like" button that changes its appearance:
import { useState } from "react";
function LikeButton() {
const [liked, setLiked] = useState(false);
function toggle() {
setLiked(!liked);
}
return (
<button onClick={toggle}>
{liked ? "Liked" : "Like"}
</button>
);
}
export default LikeButton;The process always follows the same three-step pattern. The user clicks, thetogglehandler runs and updates state usingsetLiked, then React re-renders the component with the new value. Here, the state is a boolean: the!operator reverses its value fromfalsetotrueand vice versa. The button's text depends on this value through a conditional expression inside curly braces.
A single component can have as many handlers as needed, each attached to its own element. They share the same state, allowing different buttons to modify the same data.
import { useState } from "react";
function Score() {
const [score, setScore] = useState(0);
function addPoint() {
setScore((previous) => previous + 1);
}
function removePoint() {
setScore((previous) => previous - 1);
}
function reset() {
setScore(0);
}
return (
<div>
<p>Score: {score}</p>
<button onClick={addPoint}>+1</button>
<button onClick={removePoint}>-1</button>
<button onClick={reset}>Reset</button>
</div>
);
}
export default Score;Each handler performs one task and has a name that describes it. The first two use the functional update form introduced in the state lesson because the new value depends on the previous one. The last simply replaces the value with zero.
The handler automatically receives an event objectthat describes what happened. For example, with an input field,e.target.valuecontains the current text:
import { useState } from "react";
function Echo() {
const [text, setText] = useState("");
function handleTyping(e) {
setText(e.target.value);
}
return (
<div>
<input onChange={handleTyping} placeholder="Type something" />
<p>You typed: {text}</p>
</div>
);
}
export default Echo;In this code, the parametereis the event object. Itstargetproperty refers to the element that triggered the event, in this case the input field, whilevaluecontains its content. With every keystroke, the state is updated and the paragraph changes in real time. The nameeis just a convention: you can also writeevent.

The event object has many properties, but only a few are needed in the vast majority of cases.
e.target: the element on which the event occurred.e.target.value: the content of an input field.e.type: the event's name, such as "click" or "change".e.key: for a keyboard event, the key pressed, such as "Enter".e.preventDefault(): a method that prevents the browser's default behavior.To see this for yourself, simply writeconsole.log(e)inside a handler, trigger the event, and check the browser console. You will see all the available information.
TheonKeyDownevent gives you access to the key that was pressed. This is useful for confirming an input with the Enter key, as in a search field.
import { useState } from "react";
function Search() {
const [text, setText] = useState("");
const [search, setSearch] = useState("");
function handleKey(e) {
if (e.key === "Enter") {
setSearch(text);
}
}
return (
<div>
<input
value={text}
onChange={(e) => setText(e.target.value)}
onKeyDown={handleKey}
placeholder="Type and press Enter"
/>
<p>Last search: {search}</p>
</div>
);
}
export default Search;This component uses two state variables: one for the text being typed in real time and another for the confirmed search. The first updates with every keystroke throughonChange, while the second updates only when Enter is pressed. The input has two handlers, and nothing prevents you from attaching even more to the same element.
To send a value to your function (for example, an item's ID), wrap the call inside an arrow function:
function Greetings() {
function greet(firstName) {
alert("Hi " + firstName + "!");
}
return (
<div>
<button onClick={() => greet("Aina")}>Greet Aina</button>
<button onClick={() => greet("Tiana")}>Greet Tiana</button>
</div>
);
}The arrow function() => greet("Aina")is itself the function passed toonClick. It only runs when the button is clicked, and only then does it callgreetwith the desired argument. This technique is very useful for reusing the same function with different values, such as in a list of buttons.
Sometimes, you need both a custom value and the event object. In that case, the arrow function receives the event and passes it, along with your argument, to the final function.
import { useState } from "react";
function Colors() {
const [color, setColor] = useState("white");
function choose(newColor, e) {
console.log("Event:", e.type);
setColor(newColor);
}
return (
<div style={{ backgroundColor: color, padding: 16 }}>
<button onClick={(e) => choose("tomato", e)}>Red</button>
<button onClick={(e) => choose("lightgreen", e)}>Green</button>
</div>
);
}The arrow function declares the parametere, which React provides when the click occurs, then passes it tochoosealong with the color. This follows the same principle as before: everything inside the arrow function runs only when clicked.
Some events have a default behavior: submitting a form reloads the page, and clicking a link navigates to another page. You can prevent this usinge.preventDefault(), as you will see in the lesson about forms.
This default behavior comes from the browser and existed long before React. In a React application, we almost never want to reload the entire page: we prefer to stay in control and update the interface ourselves. That is whypreventDefaultis called in most form submission handlers.
import { useState } from "react";
function Registration() {
const [name, setName] = useState("");
const [message, setMessage] = useState("");
function submit(e) {
e.preventDefault(); // prevents the page from reloading
setMessage("Thank you " + name + ", your registration has been saved.");
setName("");
}
return (
<form onSubmit={submit}>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Your name"
/>
<button type="submit">Register</button>
<p>{message}</p>
</form>
);
}
export default Registration;Withoute.preventDefault(), the browser would reload the page as soon as the form was submitted, and all the component's state would be lost: the message would not even have time to appear. Also notice that the event is attached to the form usingonSubmitrather than to the button. This way, pressing Enter inside the input also submits the form.
When you click an element, the event does not stop there: it "bubbles up" to parent elements, like a bubble rising to the surface of water. This is calledevent propagation or bubbling. If a parent also has anonClickhandler, it will run after the child's handler.
function Propagation() {
return (
<div onClick={() => console.log("Box clicked")}>
<button onClick={() => console.log("Button clicked")}>
Click
</button>
</div>
);
}
// Clicking the button displays, in this order:
// "Button clicked"
// "Box clicked"This behavior is often useful, but it can be surprising: you think you are clicking a button, yet you also trigger the container's action. To stop the event from bubbling up, calle.stopPropagation()inside the child's handler.
function StoppedPropagation() {
function handleButtonClick(e) {
e.stopPropagation(); // the parent will not be notified
console.log("Button clicked");
}
return (
<div onClick={() => console.log("Box clicked")}>
<button onClick={handleButtonClick}>Click</button>
</div>
);
}Do not confuse the two event object methods:preventDefault()prevents the browser's default behavior (reloading the page, following a link), whilestopPropagation()prevents the event from bubbling up to parent elements. They are independent: you can use either one or both.
Let's combine the concepts from this lesson into a single component: multiple fields usingonChange, form submission usingonSubmitandpreventDefault, and a button that changes the display based on a boolean state.
import { useState } from "react";
function Login() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [visible, setVisible] = useState(false);
const [error, setError] = useState("");
const [message, setMessage] = useState("");
function submit(e) {
e.preventDefault();
if (email.trim() === "" || password === "") {
setError("Please fill in all fields.");
setMessage("");
return;
}
setError("");
setMessage("Logging in as " + email + "...");
}
return (
<form onSubmit={submit}>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<label htmlFor="password">Password</label>
<input
id="password"
type={visible ? "text" : "password"}
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="button" onClick={() => setVisible(!visible)}>
{visible ? "Hide" : "Show"}
</button>
<button type="submit">Log in</button>
{error !== "" && <p>{error}</p>}
{message !== "" && <p>{message}</p>}
</form>
);
}
export default Login;valueandonChange.button; otherwise, a button inside a form would submit it. Its handler toggles the boolean state, which changes the input field's type.submithandler first prevents the page from reloading, checks the fields, then updates the error and message states.Take time to test this component and modify the code: removepreventDefaultto observe the page reload, or removetype="button"to see the "Show" button submit the form.
TheonMouseEnterandonMouseLeaveevents work as a pair: the first is triggered when the pointer enters an element, and the second when it leaves. Combined with boolean state, they can highlight an element.
import { useState } from "react";
function Card() {
const [hovered, setHovered] = useState(false);
const style = {
padding: 16,
borderRadius: "12px",
border: "1px solid #94a3b8",
backgroundColor: hovered ? "#e0f2fe" : "white",
};
return (
<div
style={style}
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
<p>{hovered ? "You are hovering over me!" : "Hover over me."}</p>
</div>
);
}
export default Card;Here, we do not use the event object because we already know the value we want to store:truewhen the pointer enters andfalsewhen it leaves. For simple visual effects like this, a CSS rule using:hoveris often simpler. State becomes useful when hovering must also change content or trigger additional logic.
Technically, you can attach anonClickhandler to any element, including adiv. However, for a clickable action, always use a realbutton. It is accessible from the keyboard without additional work (Tab, Enter, and Space keys), is correctly announced by screen readers, and has built-in focus styling. A clickablediv, on the other hand, is not accessible by default to people who do not use a mouse.
// Avoid: not keyboard-accessible
<div onClick={add}>Add</div>
// Prefer: a real button
<button onClick={add}>Add</button>When nothing happens after a click, follow these simple steps. They solve the vast majority of cases.
onclickis ignored by React.console.log(e.target.value)shows what the field actually contains.onClick={sayHello()}executes the function during rendering.onClick, notonclick.e, you cannot read an input field's value.useState.onClick="sayHello()"as in HTML does not work in JSX; you need curly braces and a function.Exercise
import { useState } from "react";
function CharacterCounter() {
const [text, setText] = useState("");
return (
<div>
<input
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Type here"
/>
<p>{text.length} character(s)</p>
</div>
);
}
export default CharacterCounter;Exercise 2: A Button That Changes Its Text
import { useState } from "react";
function ClickButton() {
const [clicks, setClicks] = useState(0);
return (
<button onClick={() => setClicks((previous) => previous + 1)}>
{clicks === 0 ? "Click" : "Already clicked (" + clicks + ")"}
</button>
);
}Go Further
import { useState } from "react";
function ColorBox() {
const [color, setColor] = useState("white");
function change(newColor) {
setColor(newColor);
}
return (
<div>
<div style={{ backgroundColor: color, height: 80 }} />
<button onClick={() => change("tomato")}>Red</button>
<button onClick={() => change("lightgreen")}>Green</button>
<button onClick={() => change("lightblue")}>Blue</button>
</div>
);
}onClick={doSomething()} to execute doSomething when clicked.onChange is triggered only when the user leaves the field.Answers: False (with parentheses, the function runs during rendering); true; true; false (in React, it is triggered whenever the value changes).
=>, useful for delaying a function call.onClick.e.target.valueand to the pressed key usinge.key.e.preventDefault().