CodePark/ questions / TypeScript with React
START PRACTICINGPRACTICE
Frontend question · TypeScript › TypeScript with React

How do you type event handlers in React, for example an input's onChange and a button's onClick?

function Search() {
  const [query, setQuery] = useState("");

  function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    setQuery(e.target.value);
  }

  function handleClick(e: React.MouseEvent<HTMLButtonElement>) {
    console.log(e.clientX);
  }

  return <><input value={query} onChange={handleChange} /><button onClick={handleClick}>Go</button></>;
}

Use React's event types, with the element type as the generic: React.ChangeEvent<HTMLInputElement> for an input's onChange, and React.MouseEvent<HTMLButtonElement> for a button's onClick.

React wraps DOM events in its own synthetic event types. Each one is generic over the element.

  • With React.ChangeEvent<HTMLInputElement>, e.target.value is a string.
  • There are also React.KeyboardEvent, React.FocusEvent and others.

If you write the handler inline, as in onChange={(e) => setQuery(e.target.value)}, you need no annotation. TypeScript infers the type from the prop. Tip: when you are not sure of the type, write the handler inline first and hover over e in the editor.

You can also type the whole function with handler types, like React.ChangeEventHandler<HTMLInputElement>.

  • Use React.ChangeEvent<HTMLInputElement> for input changes.
  • Use React.MouseEvent<HTMLButtonElement> for button clicks.
  • React event types are generic over the element type.
  • Inline handlers get their event type inferred automatically.
  • Handler types like React.ChangeEventHandler type the whole function.