← Back to React, page 3

react-0051 · Easy fresher

How do you type props, children and event handlers in a React component with TypeScript?

Declare the props as a type or interface and annotate the function parameter. Use ReactNode for children, React's event types such as ChangeEvent<HTMLInputElement> for handlers, and a function type for callback props. You usually do not need React.FC. Let TypeScript infer the return type and the state type, and annotate only where inference is not enough.

Full answer

Typing a component means describing its inputs. Write a type for the props and use it on the parameter: function Badge({ label, tone }: BadgeProps). Optional props use a question mark. A prop that accepts only certain strings uses a union such as 'info' | 'warning', which gives autocomplete and compile errors for typos.

Children can be anything React renders: text, elements, arrays, null. The type for that is ReactNode. Add children: ReactNode to props that accept content. Use ReactElement only when you need exactly one element.

Event handlers have types from React: MouseEvent<HTMLButtonElement>, ChangeEvent<HTMLInputElement>, FormEvent<HTMLFormElement>, KeyboardEvent<HTMLInputElement>. The generic argument names the element, so event.currentTarget.value is typed as string. For a callback prop, type the function: onSelect: (id: number) => void. When the handler is written inline in JSX, TypeScript infers the event type from the attribute and you write no annotation.

React.FC is not required. It used to add implicit children, which was removed, and a plain function with typed props is simpler and works better with generics. Do not annotate the return type unless you want to restrict it.

To reuse the props of a native element, extend them: ComponentProps<'button'> gives every button attribute, and you can add your own.

Type checking happens at build time only. It does not validate data at runtime, so data from an API still needs validation with a schema library.

tsx
import { useState, type ChangeEvent, type ComponentProps, type ReactNode } from 'react';

type Tone = 'info' | 'warning';

type BadgeProps = {
  label: string;
  tone?: Tone;
  children?: ReactNode;
};

function Badge({ label, tone = 'info', children }: BadgeProps) {
  return (
    <span data-tone={tone}>
      {label}
      {children}
    </span>
  );
}

type SaveButtonProps = ComponentProps<'button'> & { busy?: boolean };

function SaveButton({ busy = false, children, ...rest }: SaveButtonProps) {
  return (
    <button {...rest} disabled={busy || rest.disabled}>
      {busy ? 'Saving...' : children}
    </button>
  );
}

export default function Profile() {
  const [name, setName] = useState('');

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

  return (
    <div>
      <input value={name} onChange={handleChange} />
      <Badge label="Name length: " tone={name.length > 5 ? 'warning' : 'info'}>
        {name.length}
      </Badge>
      <SaveButton type="submit" onClick={() => console.log('saved ' + name)}>
        Save
      </SaveButton>
    </div>
  );
}

The file passed the TypeScript compiler in strict mode (tsc 7.0.2) and then ran after esbuild removed the types. The check typed a name and pressed Save. Output: saved Asha Rendered result: <div><input value="Asha"><span data-tone="info">Name length: 4</span><button type="submit">Save</button></div>

Key points

  • Describe props with a type or interface and annotate the parameter.
  • Use ReactNode for children, and unions for a closed set of strings.
  • Event types take the element as a generic: ChangeEvent<HTMLInputElement>.
  • Callback props are function types such as (id: number) => void.
  • React.FC is optional. ComponentProps<'button'> reuses native attributes.

Common mistakes

  • Typing event handlers with any, which loses currentTarget.value typing.
  • Using ReactElement for children and rejecting strings.
  • Copying a whole props interface instead of extending ComponentProps.
  • Trusting types for API data, which are not checked at runtime.
  • Using non-null assertions to silence errors that point to a real missing value.

Follow-ups

  • How do you type a component that accepts any native button attributes plus its own?
  • What is the difference between ReactNode and ReactElement?
  • How would you validate API data at runtime and derive the TypeScript type from it?

Tips

  • Show ReactNode and an event type. They are the two most common first questions.
  • Say React.FC is optional and why. It signals current practice.
  • Remember to say that types vanish at runtime.