CPCODELAB
React

Event Handling

8 min read

Handling User Events

React uses synthetic events — a cross-browser wrapper around native DOM events. Event handlers are passed as props, using camelCase names: onClick, onChange, onSubmit, onKeyDown, etc.

jsx
function LikeButton() {
  const [liked, setLiked] = useState(false);

  function handleClick(event) {
    event.preventDefault();
    setLiked(prev => !prev);
  }

  return (
    <button onClick={handleClick}>
      {liked ? "❤️ Liked" : "🤍 Like"}
    </button>
  );
}

Passing arguments to handlers

To pass extra data to a handler, wrap it in an arrow function. Avoid calling the function directly (onClick={handleDelete(id)}) — that would execute it on every render instead of on click.

jsx
function TodoItem({ id, label, onDelete }) {
  return (
    <li>
      {label}
      <button onClick={() => onDelete(id)}>Delete</button>
    </li>
  );
}
Ready to test yourself?
Practice React— quiz & coding exercises