Skip to content
jshacks.dev
TypeScript

Type an event handler in React

Type a separate handler with ChangeEvent of HTMLInputElement so event.target.value is a string, and let inline handlers infer it. React 19.

1 min read
Summarize in AI

Inline handlers get their event type for free. A handler you declare separately does not, and event becomes an implicit any until you give it a type.

Search.tsxTSX
import type { ChangeEvent } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';

type SearchProps = { onSearch: (query: string) => void };

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

  return <input type="search" onChange={handleChange} />;
}

console.log(renderToStaticMarkup(<Search onSearch={() => {}} />));
Text
<input type="search"/>

ChangeEvent<HTMLInputElement> says the event came from an input, so event.target.value is a string. For a select use HTMLSelectElement, and for a click MouseEvent<HTMLButtonElement>. If you write the handler inline, as in onChange={(e) => onSearch(e.target.value)}, the type is inferred from the prop. See the React TypeScript guide.

The server render shows the markup only, because event handlers do not run there. Type the handler itself with React.ChangeEventHandler<HTMLInputElement> when you pass it around as a value. Do not type events as any or Event: the DOM Event has no target.value, which is why people reach for any.

Also inFrameworks
Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.