Lesson 7 / 1164%

Lesson 7

Handling Events

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

  • Attach a handler to an element using onClick and other event attributes.
  • Understand the difference between passing a function and calling it.
  • Update state from an event handler to refresh the display.
  • Read the event object, including an input's value or the key pressed.
  • Pass an argument and prevent the browser's default behavior.

Responding to User Actions

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.

The Most Common Events

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.

  • Mouse:onClick,onDoubleClick,onMouseEnter,onMouseLeave.
  • Keyboard:onKeyDown(key pressed),onKeyUp(key released).
  • Form fields:onChange(value changes),onFocus(field receives focus),onBlur(field loses focus).
  • Form: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.

Your First Handler: onClick

a responsive button
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.

Passing or Calling: Three Ways to Compare

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.

three forms, three behaviors
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.

Named Handler or Inline Handler

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.

named or inline
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 and State

Events become truly useful when they update state. Here is a "Like" button that changes its appearance:

a Like button
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 Counter with Multiple Handlers

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.

three buttons, one state variable
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 Event Object

The handler automatically receives an event objectthat describes what happened. For example, with an input field,e.target.valuecontains the current text:

reading an input field's value
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.

GIF of the Echo component: text is entered into an input field, and the paragraph below updates in real time.

What Does the Event Object Contain?

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.

Responding to a Keyboard Key

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.

confirming with the Enter key
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.

Passing an Argument to a Handler

To send a value to your function (for example, an item's ID), wrap the call inside an arrow function:

handler with an argument
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.

Using an Argument and the Event Object Together

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.

passing the event and an argument
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.

Preventing Default Behavior

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.

a form that does not reload the page
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.

Event Propagation

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.

a click that bubbles up
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.

stopping event propagation
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.

Complete Example: A Login Form

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.

login form
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;

Step-by-Step Explanation

  • Five state variables: one for each piece of information (email, password, visibility, error, message). Each field is connected to its state usingvalueandonChange.
  • The "Show" button: it has the typebutton; otherwise, a button inside a form would submit it. Its handler toggles the boolean state, which changes the input field's type.
  • Submission: thesubmithandler first prevents the page from reloading, checks the fields, then updates the error and message states.
  • Conditional rendering: the error and message paragraphs appear only when their values are not empty.

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.

Example: Responding to Mouse Hover

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.

a card that responds to hover
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.

Using the Right HTML Element

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 this, prefer that
// Avoid: not keyboard-accessible
<div onClick={add}>Add</div>

// Prefer: a real button
<button onClick={add}>Add</button>

Debugging an Event Handler That Does Not Work

When nothing happens after a click, follow these simple steps. They solve the vast majority of cases.

  • Add a console.log at the beginning of the handler: if nothing appears in the console, the function is never called.
  • Check the attribute name: a lowercaseonclickis ignored by React.
  • Check the parentheses: you must pass the function, not its result.
  • Log the received value:console.log(e.target.value)shows what the field actually contains.
  • Read the browser console: a red error message almost always indicates the file and line causing the problem.

Common Mistakes

  • Calling the function instead of passing it: writingonClick={sayHello()}executes the function during rendering.
  • Incorrectly writing the event name: in JSX, useonClick, notonclick.
  • Forgetting the event parameter: withoute, you cannot read an input field's value.
  • Updating state without its setter function: always use the function provided byuseState.
  • Passing a string instead of a function: writingonClick="sayHello()"as in HTML does not work in JSX; you need curly braces and a function.
  • Forgetting preventDefault in a form: the page reloads when submitted, and state is lost.

Exercises

Exercise

Create a component with an input field and a paragraph that displays the number of typed characters in real time.
suggested solution for exercise 1
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

Create a button that displays "Click". After the first click, it should display "Already clicked" and the total number of clicks.
suggested solution for exercise 2
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

Create three buttons labeled "Red", "Green", and "Blue" that change the background color of a box, using a single function that receives the color as an argument.
suggested solution for 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>
  );
}

True or False?

  • We write onClick={doSomething()} to execute doSomething when clicked.
  • The handler automatically receives the event object.
  • To pass an argument, we wrap the call in an arrow function.
  • An input field's 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).

Quick Glossary

  • Event: an action that occurs on a page, such as a click.
  • Handler: the function executed when an event occurs.
  • Event object: the object passed to the handler that describes what happened.
  • Arrow function: a function written using =>, useful for delaying a function call.

Key Takeaways

  • An event handler is a function attached to an element using an attribute such asonClick.
  • Pass the function without calling it: do not add parentheses after its name.
  • Events are mainly used to update state, which refreshes the interface.
  • The event object provides access to an input's value usinge.target.valueand to the pressed key usinge.key.
  • To pass an argument, use an arrow function. To prevent default browser behavior, usee.preventDefault().