Type of Children Props in React with TypeScript


By onjsdev

INTRODUCTION

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 props in React with TypeScript. Let's get started.

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 props 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 props 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

You have probably saw other type named ReactElement. Let's see differences between react node and react element.

ReactElement is another type in TypeScript that can be used to define the type of children props 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 children props in React with TypeScript is an important step in ensuring that our components are type-safe and behave as expected. By using the React.ReactNode type, you can ensure that our components only accept valid React nodes as children.

Thank you for reading.