Skip to the content

Lesson 171 of 296

Typing React with TypeScript

What you will learn

  • Typing props, children and default props
  • Typing state
  • Typing events and handlers
  • Typing refs
  • Extending native element props
  • Generic components
On this page

Props

TSX
type BadgeProps = {
  label: string;
  tone?: "neutral" | "success" | "danger";
};

function Badge({ label, tone = "neutral" }: BadgeProps) {
  return <span className={`badge badge-${tone}`}>{label}</span>;
}

Most teams type props with a type or interface and destructure them. Avoid the older React.FC style: it is not wrong, but it adds little.

Children

TypeAccepts
ReactNodeAnything renderable: elements, strings, numbers, null, arrays. The usual choice.
ReactElementExactly one React element
PropsWithChildren<P>Adds children?: ReactNode to props P

State

useState infers from the initial value. Write the type when the initial value does not show the full type:

TSX
type Account = { id: string; email: string };

function AccountMenu() {
  const [account, setAccount] = useState<Account | null>(null);
  const [ids, setIds] = useState<string[]>([]);
  return (
    <button type="button" onClick={() => { setAccount({ id: "1", email: "a@b.com" }); setIds(["1"]); }}>
      {account?.email ?? "Sign in"} {ids.length}
    </button>
  );
}

Without <string[]>, an empty array would be typed never[], and adding items would fail.

Events

EventType
Input changeChangeEvent<HTMLInputElement>
Select changeChangeEvent<HTMLSelectElement>
Form submitFormEvent<HTMLFormElement> (or SubmitEvent in newer type definitions)
ClickMouseEvent<HTMLButtonElement>
Key pressKeyboardEvent<HTMLInputElement>

Import them from "react", not the DOM globals of the same name. Writing the handler inline (onChange={(e) => ...}) lets TypeScript infer the type, so you only need these when defining handlers separately.

Refs

TSX
function VideoPlayer({ src }: { src: string }) {
  const videoRef = useRef<HTMLVideoElement>(null);
  return (
    <>
      <video ref={videoRef} src={src} />
      <button type="button" onClick={() => videoRef.current?.play()}>Play</button>
    </>
  );
}

Extending native element props

A custom button should accept every normal button attribute (disabled, type, aria-*, onClick):

TSX
import type { ComponentProps } from "react";

type ButtonProps = ComponentProps<"button"> & {
  variant?: "primary" | "secondary";
};

function Button({ variant = "primary", className = "", ...rest }: ButtonProps) {
  return <button type="button" className={`btn btn-${variant} ${className}`.trim()} {...rest} />;
}

ComponentProps<"button"> is every prop a <button> accepts. To remove one, use Omit (Lesson 111): Omit<ComponentProps<"input">, "size">.

Generic components

A component can be generic (Lesson 109), so the type of items flows into renderItem:

TSX
type ListProps<T> = {
  items: T[];
  getKey: (item: T) => string;
  renderItem: (item: T) => ReactNode;
};

function List<T>({ items, getKey, renderItem }: ListProps<T>) {
  return <ul>{items.map((item) => <li key={getKey(item)}>{renderItem(item)}</li>)}</ul>;
}

function PeopleList() {
  const people = [{ id: "1", name: "Sam" }, { id: "2", name: "Ali" }];
  return <List items={people} getKey={(p) => p.id} renderItem={(p) => <strong>{p.name}</strong>} />;
}

In renderItem, p is automatically typed as { id: string; name: string }.

Typing context and reducers

Covered in Lesson 169: createContext<Value | null>(null) plus a custom hook that throws, and a discriminated union for reducer actions.

How to say it in an interview

"I type props with a type alias and destructure them with defaults, using ReactNode for children. I give useState an explicit type when the initial value is null or an empty array. Event handlers use React's event types like ChangeEvent of HTMLInputElement, and refs use useRef of the element type with null. For wrapper components I extend ComponentProps of the native element so all attributes pass through, and I write generic components like a List of T where the item type flows into the render function."

Key words

WordMeaning
ReactNodeType for anything React can render
ComponentPropsAll props accepted by an element or component
Generic componentA component with a type parameter
Event typesChangeEvent, MouseEvent, FormEvent and others from React

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.