DEV Community

Elham Najeebullah
Elham Najeebullah

Posted on

React & TypeScript: What is ReactNode and when to use it?

In ReactJS with TypeScript, ReactNode is a type that represents a React element, an array of React elements, or a string, number, or boolean. It is defined in the react module and can be used to specify the type of a variable that can hold any of these types.

Here is an example of how ReactNode can be used in a functional component with TypeScript:

import React, { ReactNode } from 'react';

function MyComponent(props: { children: ReactNode }) {
  return <div>{props.children}</div>;
}
Enter fullscreen mode Exit fullscreen mode

In this example, the children prop of the MyComponent function is declared as type ReactNode, which means that it can hold any React element, an array of React elements, or a string, number, or boolean.

ReactNode is useful when you want to specify that a prop or variable can hold any type of content that can be rendered by React, but you don't want to specify a more specific type. For example, you might use ReactNode when you want to allow a prop to hold a string, a number, an element, or an array of elements.

It is important to note that ReactNode does not include the null or undefined values, so if you want to allow these values, you will need to use the React.ReactNode type instead of just ReactNode.
Want to learn more about React with Typescript

Have any question, please leave a comment.

Top comments (2)

Collapse
 
banditos86 profile image
Alexandr Valentinov

Nice clarification. Thank You.

Collapse
 
mhasan profile image
Mahmudul Hasan

Nice clarification. Thank You.