Event Handlers

camelCase Prop, Function Value

Event Handlers

In React, you attach event handlers by passing a function as a prop like `onClick`. No `addEventListener`, no strings.

4 min read Level 1/5 #react#events#onclick
What you'll learn
  • Attach common event handlers
  • Use the event object
  • Prevent default and stop propagation

React events look just like DOM events, but you wire them up with JSX props instead of addEventListener.

Wire One Up

function SayHi() {
  function handleClick() {
    console.log("clicked!");
  }
  return <button onClick={handleClick}>Click me</button>;
}

You pass a function to onClick, not a string. The function is called when the event fires.

Inline Arrow Functions

For short handlers, inline:

<button onClick={() => console.log("clicked!")}>Click me</button>

Either style is fine. Pull out a named function when the logic grows.

The Most Common Events

Event propFires when…
onClickElement is clicked
onChangeInput value changes
onSubmitForm is submitted
onInputInput gets typed into (every keystroke)
onKeyDownA key goes down
onFocus / onBlurElement gains/loses focus
onMouseEnter / onMouseLeaveMouse enters/leaves
onPointerDownPointer down (mouse, touch, pen — unified)

camelCase props throughout — onClick, not onclick.

The Event Object

The handler receives a synthetic event — React’s wrapper around the native event. The API matches the DOM (.target, .key, preventDefault, etc.):

function Input() {
  function handleChange(e) {
    console.log(e.target.value);
  }
  return <input onChange={handleChange} />;
}

Preventing Defaults

Same as DOM:

function LoginForm() {
  function handleSubmit(e) {
    e.preventDefault();
    console.log("would submit");
  }
  return (
    <form onSubmit={handleSubmit}>
      <input name="email" />
      <button>Sign in</button>
    </form>
  );
}

onSubmit on a <form> fires when the user presses Enter inside an input or clicks a <button>. Almost every form in React needs e.preventDefault() to stop the browser from navigating.

Stopping Propagation

function Modal({ onClose }) {
  return (
    <div className="backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        Click outside to close, not inside.
      </div>
    </div>
  );
}

Don’t Call the Handler in JSX

A super common beginner mistake — and the error is silent:

// ✗ Calls handleClick on every render
<button onClick={handleClick()}>OK</button>

// ✓ Passes the function reference
<button onClick={handleClick}>OK</button>

With (), you’re saying “call this now and pass the result as the handler”. If handleClick returns nothing, onClick is undefined — and if it does anything (set state, fetch), you’ve just kicked off an infinite render loop.

Up Next

How to pass extra arguments to your handler.

Event Args →