ReactEasy

What is the children prop?

children is the special prop that holds whatever you put between a component's opening and closing tags. It lets components wrap arbitrary content, such as cards, layouts, modals and providers, which is the foundation of composition in React.

Basics

  • <Card><h2>Title</h2><p>Body</p></Card>: inside Card, props.children is that content.
  • It can be text, elements, arrays, null, or even a function (the render prop pattern).
  • Type it as React.ReactNode in TypeScript.

Why it matters

  • Composition over configuration: instead of many props (title, body, footer), let callers pass any JSX.
  • Avoid prop drilling: a parent can render the consumer directly inside a layout, so intermediate components never touch the data.
  • Server Components in Next.js: Client Components can wrap server-rendered content passed as children without turning it into client code.

Multiple slots

For more than one region, use named props: <Layout sidebar={<Nav />} header={<Header />}>{content}</Layout>.

The Children utilities

React.Children.map, Children.count and cloneElement exist but are considered legacy patterns; they are fragile with fragments and wrappers. Prefer explicit props, context, or compound components.

Gotcha

children is opaque: do not rely on inspecting its structure. If you need data, pass data.

Code example

tsx
1type ModalProps = {
2 title: string;
3 footer?: React.ReactNode; // a named slot
4 children: React.ReactNode; // the main slot
5 onClose: () => void;
6};
7
8export function Modal({ title, footer, children, onClose }: ModalProps) {
9 return (
10 <div role="dialog" aria-modal="true" aria-labelledby="modal-title" className="modal">
11 <header>
12 <h2 id="modal-title">{title}</h2>
13 <button aria-label="Close" onClick={onClose}>×</button>
14 </header>
15 <div className="modal-body">{children}</div>
16 {footer && <footer>{footer}</footer>}
17 </div>
18 );
19}
20
21export function DeleteDialog({ onClose }: { onClose: () => void }) {
22 return (
23 <Modal title="Delete project?" onClose={onClose} footer={<button className="danger">Delete</button>}>
24 <p>This cannot be undone.</p>
25 </Modal>
26 );
27}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app