React Foundations · TypeScript

Typing event handlers

Typing events

Typing event handlers

An input's change handler receives an event that carries the element which fired it. Write the handler on its own and event has no type, so event.target.value is unchecked. Annotate it with the event type instead:

import { type ChangeEvent } from 'react';

function handleChange(event: ChangeEvent<HTMLInputElement>) {
  setName(event.target.value);
}

ChangeEvent<HTMLInputElement> says the event came from an <input>, so event.target is an HTMLInputElement and .value is a string. The generic names the element, and the element type decides what .target can do.

The same pattern types every handler: FormEvent<HTMLFormElement> for a form submit, MouseEvent<HTMLButtonElement> for a button click, KeyboardEvent for a key press. The event interface is the parameter's type; the generic narrows it to the element.

<input value={name} onChange={handleChange} />

React already knows what onChange expects, so a handler annotated with the wrong event type is a compile error at the attribute — the mistake surfaces where you wrote it, not at runtime.

Your job is to type an event handler in App.tsx.

Challenge

An input's change handler needs the event's type. Export an App component from App.tsx that keeps a name in useState<string>('') and renders a text input bound to it with value and onChange. Annotate the handler with ChangeEvent<HTMLInputElement> and set the state from event.target.value. Render the current name in a paragraph.

The Test types Ada into the input and expects the paragraph to read Ada. The starter renders an input with no handler and an empty paragraph, so the Test fails.

App.tsx
export function App() {
  return (
    <div>
      <input aria-label="Name" />
      <p></p>
    </div>
  );
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.