DevAcademy
LearnReactHandling Events
BeginnerReact

Handling Events

Learn how to respond to clicks, input changes, and other user interactions in React.

Reading Time

14 min

Lesson

Lesson 7 of 42

Attaching Event Handlers

React event handlers are passed as camelCase props like onClick, and receive a function reference — not a string, and not a function call.

A Basic Click Handler

function Button() {
  function handleClick() {
    alert("Button clicked!");
  }

  return <button onClick={handleClick}>Click me</button>;
}

Passing a Function Reference, Not Calling It

onClick={handleClick} passes the function itself, to be called later by React. onClick={handleClick()} calls it immediately during render instead — a very common beginner mistake.

Passing Arguments with an Inline Arrow Function

function ItemList({ items, onRemove }) {
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>
          {item.name}
          <button onClick={() => onRemove(item.id)}>Remove</button>
        </li>
      ))}
    </ul>
  );
}

The Event Object

React passes a synthetic event object to handlers, normalized to behave consistently across browsers, with the same familiar properties and methods as a native DOM event.

Reading the Event Object

function SearchInput() {
  function handleChange(event) {
    console.log(event.target.value);
  }

  return <input onChange={handleChange} placeholder="Search..." />;
}

Common Event Props

PropFires When
onClickAn element is clicked
onChangeA form input’s value changes
onSubmitA form is submitted
onKeyDownA key is pressed down
onMouseEnter / onMouseLeaveThe pointer enters/leaves an element
onFocus / onBlurAn element gains or loses focus

Preventing Default Behavior

Just like native DOM events, event.preventDefault() stops a browser’s default action — most commonly used to stop a form submission from reloading the page.

preventDefault in a Form

function SearchForm() {
  function handleSubmit(event) {
    event.preventDefault();
    console.log("Form submitted without a page reload");
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" />
      <button type="submit">Search</button>
    </form>
  );
}

Best Practice

Name event handler functions starting with "handle" (handleClick, handleSubmit) — it’s a widely followed convention that makes event-driven code easy to scan at a glance.

Interview Questions

Quick Quiz

1. What is wrong with onClick={handleClick()}?

2. How do you pass an argument to an event handler in React?

3. What does event.preventDefault() commonly stop?