How to type your React Children Property in TypeScript<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to type your React Children Property in TypeScript

Posted on: February 21, 2022

When you are using TypeScript and React, a good practice is to type your property. Each component is well defined and clear with what to provide. For example:

1interface MyOptions {
2 name: string;
3}
4
5export const MyComponent = (props: MyOptions) => {
6 // ...
7};

In React, a popular pattern is allowing the use of children.

1interface MyOptions {
2 name: string
3 children?: React.ReactNode;
4}
5export const MyComponent = (props: MyOptions) => {
6 return <div>{props.children</div>;
7}

You can use several types for the children. The React.ReactNode is one that is often used, but also JSX.Element which inherently uses the React.ReactElement

If you look at the type definition of React you can see that:

1type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

and

1declare global {
2 namespace JSX {
3 interface Element extends React.ReactElement<any, any> { }

They are not the same, but in most cases are almost interchangeable. I would lean toward the ReactNode if you have no personal preference has it covers specific, explicit types and has the null/undefined for free.