Advertisement
Intermediate React, TypeScript with React

How would you type a component's children prop correctly using TypeScript?

Short answer

React provides a built in type called ReactNode that covers anything that is valid to render, including text, numbers, elements, and arrays of elements, making it the correct type to use for a children prop in most situations.

Save React mock interview
Advertisement
AModel answer
React provides a built in type called ReactNode that covers anything that is valid to render, including text, numbers, elements, and arrays of elements, making it the correct type to use for a children prop in most situations.
import { ReactNode } from 'react';

type CardProps = {
  title: string;
  children: ReactNode;
};

function Card({ title, children }: CardProps) {
  return (
    <div>
      <h2>{title}</h2>
      {children}
    </div>
  );
}
Real-world example
A shared Card component correctly accepts any valid content as its children, whether it is plain text, a single element, or several elements together, thanks to using the ReactNode type from React.
Likely follow-ups
  • What is the difference between ReactNode and the more specific ReactElement type?
  • Why should children not simply be typed as a string if it might contain other elements too?
Related topics