Skip to content

Responding to Events

The Course
•
20 min study

Today: responding to events

So far every page has been fixed: it shows what its props say, and nothing the reader does changes it. Today pages start to respond. The first step is running your code when something happens, such as a click.

Event handlers

An event handler is a function you give to an element, to run when an event happens. For a click, pass it as the onClick prop:

JSX
<button onClick={handleStart}>Start</button>

Click each button below and watch the console.

Three buttons React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); export default function App() { function handleStart() { console.log("Start pressed"); } function handleBreak() { alert("Time for a 5-minute break."); } return ( <main> <h1>Study session</h1> <button onClick={handleStart}>Start</button>{" "} <button onClick={handleBreak}>Take a break</button>{" "} <button onClick={() => console.log("Skipped to the next topic")}>Skip</button> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
  • Start runs handleStart, a function declared inside App. By convention, handler names start with handle, followed by what happened:

    JavaScript
    function handleStart() {
      console.log("Start pressed");
    }
  • Take a break calls alert. In a real browser, alert opens a dialog that blocks the whole page. The lab shows a notice over the preview instead, so the course page never freezes:

    JavaScript
    function handleBreak() {
      alert("Time for a 5-minute break.");
    }
  • Skip passes an arrow function written right in the JSX. That's convenient for a one-line handler:

    JSX
    <button onClick={() => console.log("Skipped to the next topic")}>Skip</button>
onClick, not onclick

React event props are camelCase: onClick, onChange, onSubmit, onMouseEnter. HTML's lower-case onclick="..." attribute is a string of code; React's onClick is a function.

Pass the function, don't call it

This is the most common event mistake. Change the Start button to:

JSX
<button onClick={handleStart()}>Start</button>

Predict what the console shows when you press Run, before you click anything. Then click Start a few times.

Check your prediction

Start pressed appears as soon as the app runs, before any click, and then clicking does nothing. handleStart() with brackets calls the function while React builds the page, and passes its return value, undefined, as the click handler. onClick={handleStart} passes the function itself for React to call later. Remove the brackets.

Your turn

Exercise

A topic button

Add a function logTopic(topic) to App that logs Next topic: followed by the topic. Add two buttons, Props and State. Clicking each logs its own topic, for example Next topic: Props.

Your working space React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); export default function App() { function handleStart() { console.log("Start pressed"); } function handleBreak() { alert("Time for a 5-minute break."); } return ( <main> <h1>Study session</h1> <button onClick={handleStart}>Start</button>{" "} <button onClick={handleBreak}>Take a break</button>{" "} <button onClick={() => console.log("Skipped to the next topic")}>Skip</button> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Both buttons call the same function with a different argument. Neither can write onClick={logTopic("Props")}, for the reason above: that calls it now. React calls the click handler later, and it doesn't know about your topic. So the handler has to be a new function that, when React calls it, calls logTopic with the right topic.

Hint 2: a first step

Write logTopic, then try onClick={logTopic} on the Props button and click it. The console shows Next topic: followed by an event object, not Props: React passes its click event as the first argument. You need a function that takes no argument and calls logTopic("Props") itself. Which kind of function can you write right inside the braces?

Show one solution
JavaScript
function logTopic(topic) {
  console.log("Next topic:", topic);
}
JSX
<button onClick={() => logTopic("Props")}>Props</button>{" "}
<button onClick={() => logTopic("State")}>State</button>

Each arrow function is a small handler of its own. React calls it on a click, and it then calls logTopic with the topic written inside it.

{" "} puts a space between two buttons on the same line. Without it, JSX leaves no space between them.

Was this article helpful?

Your response is saved on this device.