Rendering DataCore· 35 min read

Handling Events

Respond to clicks, typing and more — the React way, with onClick and handler functions.

What you will learn

  • Handle events with onClick and friends
  • Write handler functions
  • Pass arguments to handlers

onClick and handlers

React events look like HTML events but use camelCase (onClick, onChange) and take a function, not a string.

onClick takes a function
function App() {
  function sayHi() {
    alert("Hello from React!");
  }
  return <button onClick={sayHi}>Click me</button>;
}
Live preview

We define a function sayHi that pops up an alert. Then we hand that function to the button with onClick={sayHi}. Notice there are no parentheses after sayHi — we are giving React the function so it can call it later, when the user clicks. React only runs sayHi at the moment of the click, not while drawing the page.

Note: Output: A button labelled Click me. Click it and a browser alert pops up reading “Hello from React!”.

Watch out: Pass the function, do not call it: onClick={sayHi} (correct) vs onClick={sayHi()} (wrong — that calls it immediately on render). To pass arguments, use an arrow: onClick={() => greet("Asha")}.

Often a handler needs to know which thing was clicked. This example passes a different name to the same function from each button:

Arrow wrapper passes arguments
function App() {
  function greet(name) {
    alert("Hi, " + name + "!");
  }
  return (
    <div>
      <button onClick={() => greet("Asha")}>Greet Asha</button>
      <button onClick={() => greet("Ravi")}>Greet Ravi</button>
    </div>
  );
}
Live preview

What if the handler needs an argument, like which name to greet? You cannot write onClick={greet("Asha")} — that would run immediately. Instead you wrap it in a tiny arrow function: onClick={() => greet("Asha")}. The arrow function is what gets handed to React; only when clicked does it run and call greet("Asha"). The two buttons pass different names to the same greet function.

Note: Output: Two buttons, Greet Asha and Greet Ravi. Clicking the first alerts “Hi, Asha!”; clicking the second alerts “Hi, Ravi!”.

Q. How do you correctly attach a click handler called save?

Answer: Pass the function reference: onClick={save}. Using save() would call it during render instead of on click.

✍️ Practice

  1. Make a button that shows an alert with your name.
  2. Make two buttons that pass different arguments to one handler.

🏠 Homework

  1. Build three buttons that each log a different message to the console.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →