~/hackweb.dev
Event Handling
Quiz
...

Event Handling

beginner · updated Tue Sep 08 2026Contribute

Handle user interactions with event handlers in React.

Event Handling

React uses synthetic events that wrap the browser’s native events, providing consistent cross-browser behavior.

onClick

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

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

Pass a function reference, don’t call it: onClick={handleClick}, not onClick={handleClick()}.

onChange

function Input() {
  const [value, setValue] = useState("");

  return (
    <input
      value={value}
      onChange={(e) => setValue(e.target.value)}
    />
  );
}

The event object e gives you access to the input’s current value.

The Event Object

React events are synthetic events — thin wrappers around native events:

function Form() {
  function handleSubmit(e) {
    e.preventDefault();
    console.log(e.target.value);
  }

  return <form onSubmit={handleSubmit}>...</form>;
}

They have the same interface as native events but work identically across browsers.

Preventing Default

Use e.preventDefault() to stop default browser behavior:

function Link({ href, children }) {
  function handleClick(e) {
    e.preventDefault();
    console.log("Navigation blocked");
  }

  return <a href={href} onClick={handleClick}>{children}</a>;
}

Without it, clicking a link navigates away from the page.

Passing Arguments

Use an arrow function to pass custom arguments:

function TodoList({ items }) {
  function handleDelete(id) {
    console.log("Delete", id);
  }

  return items.map(item => (
    <li key={item.id} onClick={() => handleDelete(item.id)}>
      {item.text}
    </li>
  ));
}

Without the arrow function, handleDelete(item.id) runs on render, not on click.

Common Event Handlers

Event Handler
Click onClick
Input change onChange
Form submit onSubmit
Key press onKeyDown, onKeyUp
Mouse enter onMouseEnter
Focus onFocus, onBlur

Best Practices

  1. Use descriptive nameshandleClick, handleSubmit, not onClick
  2. Define handlers inside or outside component — Both work
  3. Use arrow functions for arguments() => handleDelete(id)
  4. Prevent default early — First line in form handlers

Common Mistakes

  1. Calling the function in JSXonClick={handleClick()} runs immediately
  2. Forgetting preventDefault — Forms submit and reload the page
  3. Using this in function components — There is no this context
  4. Not destructuring the evente.target.value requires the event param