Sub topic 4
Typing children with ReactNode
This chapter assumes you can write React function components, know what props.children is in JSX, and are comfortable with TypeScript unions and interfaces. It also assumes you have a project with strict enabled, as set up earlier in this tutorial.
Why children needs an explicit type
In JSX, anything you put between a component's opening and closing tags arrives as the children prop. TypeScript does not guess its type. Older @types/react versions added children to React.FC automatically, but version 18 removed that. A component that wants children must now declare them in its props:
import type { ReactNode } from "react";
interface CardProps {
title: string;
variant?: "plain" | "outlined";
children: ReactNode;
}
export function Card({ title, variant = "plain", children }: CardProps) {
return (
<section className={`card card-${variant}`}>
<h2>{title}</h2>
{children}
</section>
);
}If you pass children to a component that does not declare them, the compiler reports an error. This is usually what you want, because it catches <Icon>text</Icon> when Icon ignores its children.
What ReactNode includes
ReactNode is the widest type for "anything React can render." It is a union of these members:
ReactElement, which is what JSX expressions produce.stringandnumber.boolean,null, andundefined, which React renders as nothing.- Iterables of
ReactNode, such as arrays. ReactPortal.
Newer @types/react releases may add members, such as promises for server components. Check the version you have installed.
Because the union is so wide, all of these calls type-check against Card:
import { Card } from "./Card";
export function Examples({ show }: { show: boolean }) {
return (
<>
<Card title="Text">Just a string</Card>
<Card title="Number">{42}</Card>
<Card title="Conditional">{show && <p>Visible</p>}</Card>
<Card title="List">
{["a", "b"].map((x) => (
<p key={x}>{x}</p>
))}
</Card>
</>
);
}{show && <p>Visible</p>} evaluates to false or an element. Both are members of ReactNode, so no special handling is needed.
ReactNode compared with nearby types
Several similar types exist. Picking the wrong one is the most common children typing error.
| Type | Accepts | Typical use |
|---|---|---|
| `ReactNode` | Anything renderable, including text, arrays, and `null` | The `children` prop of general containers |
| `ReactElement` | Only objects created by JSX or `createElement` | A prop that must be exactly one element |
| `JSX.Element` | The result type of a JSX expression, a `ReactElement` with `any` props | Rarely needed in new code |
| `string` | Only text | Labels and button captions |
| `ReactChild` | Element, string, or number | Deprecated, avoid |
Typing children as JSX.Element is a frequent mistake. It rejects plain strings, null, and arrays, so <Card>Hello</Card> fails to compile. Use ReactNode unless you have a reason to be stricter.
Required or optional children
Whether children is required is a design decision. Declare it without ? when the component is meaningless without content, such as a Card body. Add ? when children are a bonus:
import type { ReactNode } from "react";
interface BadgeProps {
label: string;
children?: ReactNode;
}
export function Badge({ label, children }: BadgeProps) {
return (
<span className="badge">
{label}
{children ? <small>{children}</small> : null}
</span>
);
}Even a required children: ReactNode accepts null or undefined as a value, since both are part of the union. "Required" here means the prop must be supplied, either in the tags or as children={...}. It does not mean the content must be non-empty. A self-closing <Card title="x" /> fails, but <Card title="x">{null}</Card> compiles.
PropsWithChildren
PropsWithChildren<P> adds an optional children?: ReactNode to the props type P:
import type { PropsWithChildren } from "react";
type PanelProps = PropsWithChildren<{ heading: string }>;
export function Panel({ heading, children }: PanelProps) {
return (
<div className="panel">
<h3>{heading}</h3>
{children}
</div>
);
}It is concise, but it makes children optional. The explicit children: ReactNode field is clearer, and it is the only way to make children required. Use PropsWithChildren for small wrapper components where optional children are acceptable.
Restricting what children can be
Sometimes ReactNode is too permissive. TypeScript can enforce a few narrower shapes.
Text only
interface LabelProps {
children: string;
}
export function Label({ children }: LabelProps) {
return <label>{children}</label>;
}
// <Label>Name</Label> compiles
// <Label><b>Name</b></Label> error: element is not assignable to string
// <Label>Count: {3}</Label> error: children is string[]-like, not stringThe last case surprises people. A JSX expression with mixed text and an expression container produces multiple children, so React passes an array. Use a template literal, {Count: ${n}}, when you need a single string.
A single element
import type { ReactElement } from "react";
interface TooltipProps {
text: string;
children: ReactElement;
}
export function Tooltip({ text, children }: TooltipProps) {
return <span title={text}>{children}</span>;
}<Tooltip text="Help"><button>?</button></Tooltip> compiles. A string child, or two sibling elements, does not.
A render function
A component can also take a function as children. This is the render prop pattern, and TypeScript checks both the function's parameter and its return value:
import { useState, type MouseEvent, type ReactNode } from "react";
interface MouseTrackerProps {
children: (position: { x: number; y: number }) => ReactNode;
}
export function MouseTracker({ children }: MouseTrackerProps) {
const [position, setPosition] = useState({ x: 0, y: 0 });
function handleMove(e: MouseEvent<HTMLDivElement>) {
setPosition({ x: e.clientX, y: e.clientY });
}
return <div onMouseMove={handleMove}>{children(position)}</div>;
}
export function Demo() {
return (
<MouseTracker>
{({ x, y }) => (
<p>
{x}, {y}
</p>
)}
</MouseTracker>
);
}In Demo, the destructured x and y are inferred as number from the declared function type, so no annotations are needed.
What you cannot check with types
Types describe the union, not the content. You cannot declare "children must be exactly three Tab components" and have the compiler verify it. ReactElement does not carry the component type that created it. If you need that structure, pass data instead of elements, for example tabs: { label: string; content: ReactNode }[].
At runtime you can inspect children with the helpers in React.Children, but you must narrow first. ReactNode includes strings and null, which have no .props:
import { Children, isValidElement, type ReactNode } from "react";
export function countElements(children: ReactNode): number {
return Children.toArray(children).filter(isValidElement).length;
}Children.toArray flattens arrays and drops null, undefined, and booleans. isValidElement acts as a type guard, so the filtered array holds elements. This function counts elements and ignores text.
Common errors
| Error message or symptom | Cause | Fix |
|---|---|---|
| `Property 'children' does not exist on type ...` | The props type never declared `children` | Add `children: ReactNode` |
| `Type 'string' is not assignable to type 'Element'` | `children` typed as `JSX.Element` | Change to `ReactNode` |
| `Property 'children' is missing in type '{}'` | Required children and a self-closing tag | Pass content, or make `children` optional |
| `Property 'props' does not exist on type 'ReactNode'` | Reading `child.props` without narrowing | Guard with `isValidElement` first |
| Render function errors on a mixed text child | Several children became an array | Pass a single function as the only child |
Exercises
Exercise
A teammate wrote interface BoxProps { children: JSX.Element } and now <Box>Hello</Box> fails to compile. Why does it fail, and what is the one-line fix?
Show answer
A plain string is not a JSX.Element, which only describes the result of a JSX expression. Change the field to children: ReactNode (imported as a type from "react"), which also accepts strings, numbers, arrays, null, and undefined.
Exercise
Write the props type for a List component whose only child must be a function that receives a string[] of names and returns anything renderable. Then say why <List>{names.length}</List> is rejected.
Show answer
interface ListProps { children: (names: string[]) => ReactNode }. The call <List>{names.length}</List> is rejected because a number is not assignable to a function type. Number would be valid for ReactNode, but children is declared as a function here.