Different ways the React children prop can be typed with TypeScript

The React children prop allows components to be composed together and is a key concept for building reusable components. Visually, we can think of it as a hole in the component where the consumer controls what is rendered. This post covers different approaches to strongly-typing this powerful and flexible prop with TypeScript.

Using the FC type

There is a standard React type, FC, that we can use on arrow function components. FC stands for Function Component, and it aliases a type called FunctionComponent.

Here’s an example:

type Props = {
  title: string,
};
const Page: React.FC<Props> = ({
  title,
  children,
}) => (
  <div>
    <h1>{title}</h1>
    {children}
  </div>
);

FC is a generic type that takes in the specific type for all the component props. In the example above, we passed in a Props type alias containing a title prop. Alternatively, an interface could be used to define Props.

Notice that children isn’t defined in Props. Instead, it is already defined in the FC type. This is nice if you know this fact, but it might be a bit confusing if you don’t.

#react #typescript #javascript #programming #developer

React Children with TypeScript
18.80 GEEK