Onjsdev

Share


Children Prop type

What is the Children Prop Type In React With TypeScript?


By onjsdev

Nov 25th, 2023

TypeScript is a typed superset of JavaScript that adds static typing and other features to the language. When working with React in TypeScript, it is important to define the types of the props that are passed down to child components.

In this article, we will explore how to define the type of children prop in React with TypeScript.

Type of Children Props

In React, children are a special type of prop that allow us to pass components, text or other content to a component. Children can be defined using the props.children property in a React component.

With TypeScript, we can define the type of children prop using the `ReactNode type. The ReactNode type is a union type that can represent any valid React node, including elements, text and other content.

Here's an example of how to define the type of children prop in a TypeScript React component:

type Props = {
  children: React.ReactNode;
};

const MyComponent: React.FC<Props> = ({ children }) => {
  return <div>{children}</div>;
};

In addition to defining the type of children props, we can also define the types of other props that are passed down to child components. For example, we can define the type of a prop called className that is used to specify the CSS class of an element:

type Props = {
  children: React.ReactNode;
  className: string;
};

const MyComponent: React.FC<Props> = ({ children, className }) => {
  return <div className={className}>{children}</div>;
};

ReactNode vs ReactElement

When it comes to define an interface or prop in typescript for the react children prop, you have probably saw other type named ReactElement.

ReactElement is another type in TypeScript that can be used to define the type of children prop in React components. The ReactElement type is a more specific type than ReactNode and is used to represent a single React element (i.e. a component or HTML element) rather than a collection of nodes.

Also ReactElement type is only the type of output that functional components render, which means number, string etc. is not in the ReactElement type.

type Props = {
  children: React.ReactElement |  ReactElement[]
};

const MyComponent: React.FC<Props> = ({ children }) => {
  return <div>{children}</div>;
};

Conclusion

Defining the type of the children prop in React with TypeScript is an important point. By using the React.ReactNode type, you can ensure that our components only accept valid React nodes as children.

Thank you for reading.