Children & Composition
React's composition model is what makes it so flexible and powerful.
Instead of inheriting from base classes, you build complex UIs by
combining simple components together.
At the heart of this is props.children — the special prop
that lets one component render whatever another component passes inside it.
In this chapter you'll master props.children,
the React.Children API, the slot pattern for named regions,
compound components, render props, and
the fundamental principle: compose, don't inherit.
1. What is Component Composition?
Composition is the practice of building complex UIs by combining smaller, simpler components together — like assembling Lego bricks. Rather than creating a large monolithic component, you build small focused pieces and arrange them to form the full UI.
React is built around composition. The React team explicitly states: "We recommend using composition instead of inheritance to reuse code between components." Unlike object-oriented languages where you extend a base class to add behaviour, in React you wrap components inside other components.
SpecialButton that
inherits from Button…In React you: make a
Button that accepts
children, then use it in a
SpecialButton that wraps it.
Composition gives you more flexibility with less coupling.
<Card /> wrapper works
for a product card, a profile card, a settings panel — all without knowing what's
inside. Write the container once, fill it with anything.2. props.children — The
Automatic Content Slot
Every React component automatically receives a children
prop.
Its value is whatever JSX is placed between the component's opening and closing
tags.
You don't declare it — React populates it for you automatically.
// Alert component — doesn't know what message it'll show
function Alert({ type = 'info', children }) {
return (
<div className={`alert alert-${type}`}>
{children}
</div>
);
}
// ── children can be ANYTHING ──────────────────────────────────
<Alert type="success">
Your profile was saved! ✅ {/* string */}
</Alert>
<Alert type="warning">
<strong>Heads up:</strong> Your session expires soon. {/* JSX */}
</Alert>
<Alert type="error">
<ul>
<li>Email is required</li>
<li>Password too short</li> {/* complex structure */}
</ul>
</Alert>
children is a ReactNode — it can be a
string, number, a single React element, an array of elements, a Fragment, or null/undefined.
If nothing is placed between the tags, children is undefined.
Use a default value or check with React.Children.count(children) before operating on it.
// children is undefined <Card /> // Same — children still undefined <Card></Card>
// children = <p>Hello</p> <Card> <p>Hello World</p> </Card> // children = "Hello" (a string) <Card>Hello</Card>
3. Containment Pattern — Wrapper Components
The containment pattern is when a component acts as a generic container that provides structure (border, padding, header bar, shadow) while the content is fully controlled by the parent. This is the most common and most useful pattern in React.
// ── CONTAINER: provides backdrop, box, close button ──────────
function Modal({ isOpen, onClose, children }) {
if (!isOpen) return null;
return (
<div className="modal-backdrop">
<div className="modal-box">
<button className="modal-close" onClick={onClose}>✕</button>
{children} {/* ← parent decides what goes inside */}
</div>
</div>
);
}
// ── USAGE 1: Login form inside Modal ─────────────────────────
<Modal isOpen={showLogin} onClose={() => setShowLogin(false)}>
<h2>Sign In</h2>
<LoginForm />
</Modal>
// ── USAGE 2: Confirmation dialog inside same Modal ────────────
<Modal isOpen={showConfirm} onClose={() => setShowConfirm(false)}>
<p>Are you sure you want to delete this item?</p>
<button onClick={handleDelete}>Delete</button>
</Modal>
The same <Modal /> component is reused for a login
form
and a confirmation dialog — completely different content, same wrapper.
This is the power of the containment pattern.
4. Named Slots — Multiple Content Regions
Sometimes one children slot isn't enough.
A page layout might need a header, a sidebar,
and a main body — all injected separately.
React doesn't have a built-in slot system like Vue, but you can achieve the same
thing with regular named props that accept JSX.
// ── LAYOUT COMPONENT: defines named regions ───────────────────
function PageLayout({ header, sidebar, children, footer }) {
return (
<div className="page">
<header className="page-header">{header}</header>
<div className="page-body">
<aside className="page-sidebar">{sidebar}</aside>
<main className="page-main">{children}</main>
</div>
<footer className="page-footer">{footer}</footer>
</div>
);
}
// ── USAGE: pass JSX to each named slot ───────────────────────
function App() {
return (
<PageLayout
header={<Navbar />}
sidebar={<FilterPanel />}
footer={<SiteFooter />}
>
{/* children = main page content */}
<ProductGrid />
</PageLayout>
);
}
header={'{'}<Navbar />{'}'} is exactly the same as
header={'{'}navbar_element{'}'} where the variable holds a
React element.
5. React.Children API
Sometimes you need to inspect or transform the children passed to your component —
count them, map over them, clone them with extra props, or enforce a single child.
React provides the React.Children utility for exactly this.
It handles all the edge cases of children being undefined,
a single element, or an array.
import React from 'react';
// TabGroup injects an "index" prop into each Tab child
function TabGroup({ children, activeTab, onTabChange }) {
const tabs = React.Children.map(children, (child, index) =>
React.cloneElement(child, {
index,
isActive: index === activeTab,
onClick: () => onTabChange(index),
})
);
return <div className="tab-group">{tabs}</div>;
}
function Tab({ label, isActive, onClick }) {
return (
<button
className={isActive ? 'tab active' : 'tab'}
onClick={onClick}
>
{label}
</button>
);
}
// Usage — parent doesn't pass index/isActive manually
<TabGroup activeTab={active} onTabChange={setActive}>
<Tab label="Overview" />
<Tab label="Features" />
<Tab label="Pricing" />
</TabGroup>
import React from 'react';
// Show item count in a grid component
function Grid({ columns = 3, children }) {
const count = React.Children.count(children);
return (
<div>
<p>Showing {count} item{count !== 1 ? 's' : ''}</p>
<div style={{ display:'grid', gridTemplateColumns:`repeat(${columns},1fr)` }}>
{children}
</div>
</div>
);
}
// Enforce single child
function SingleChild({ children }) {
const child = React.Children.only(children); // throws if not exactly 1
return <div className="wrapper">{child}</div>;
}
6. Compound Components Pattern
Compound components are a set of components that work together
and share implicit state via React Context.
Think of the native HTML <select> and
<option> — they're separate elements
but deeply connected. You build the React equivalent with a parent that provides
context and children that consume it.
import { createContext, useContext, useState } from 'react';
// 1. Create context to share state between compound parts
const AccordionCtx = createContext(null);
// 2. Root component — owns the state, provides context
function Accordion({ children }) {
const [openId, setOpenId] = useState(null);
const toggle = (id) => setOpenId(prev => prev === id ? null : id);
return (
<AccordionCtx.Provider value={{ openId, toggle }}>
<div className="accordion">{children}</div>
</AccordionCtx.Provider>
);
}
// 3. Sub-component — reads context, no props needed
function AccordionItem({ id, title, children }) {
const { openId, toggle } = useContext(AccordionCtx);
const isOpen = openId === id;
return (
<div className="accordion-item">
<button onClick={() => toggle(id)}>
{title} {isOpen ? '▲' : '▼'}
</button>
{isOpen && <div className="accordion-body">{children}</div>}
</div>
);
}
// 4. Attach sub-components as static properties (optional DX pattern)
Accordion.Item = AccordionItem;
// ── USAGE — clean, declarative, no prop-drilling ──────────────
<Accordion>
<Accordion.Item id="q1" title="What is React?">
React is a JavaScript library for building UIs.
</Accordion.Item>
<Accordion.Item id="q2" title="What are hooks?">
Hooks let you use state in functional components.
</Accordion.Item>
</Accordion>
<Routes> + <Route>,
Headless UI's <Tab.Group> + <Tab>,
Radix UI's <Select.Root> + <Select.Item>
— all compound components. Once you spot the pattern, you'll see it everywhere.
7. Render Props Pattern
A render prop is a prop whose value is a function that returns JSX. Instead of rendering fixed content, the component calls the function and renders whatever it returns. This lets the component share logic (data fetching, mouse tracking, toggle state) while the caller decides how to display the result.
import { useState, useEffect } from 'react';
// DataFetcher handles loading/error/data — caller decides UI
function DataFetcher({ url, render }) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch(url)
.then(r => r.json())
.then(d => { setData(d); setLoading(false); })
.catch(e => { setError(e); setLoading(false); });
}, [url]);
// Call the render prop — pass state to the caller
return render({ data, loading, error });
}
// ── USAGE 1: show a user list ─────────────────────────────────
<DataFetcher
url="/api/users"
render={({ data, loading, error }) => {
if (loading) return <p>Loading users…</p>;
if (error) return <p>Error: {error.message}</p>;
return <UserList users={data} />;
}}
/>
// ── USAGE 2: same logic, different UI (product table) ─────────
<DataFetcher
url="/api/products"
render={({ data, loading }) =>
loading ? <Spinner /> : <ProductTable products={data} />
}
/>
A popular variant is using children itself as the render
function
— this is sometimes called "function as children":
function Toggle({ children }) {
const [isOn, setIsOn] = useState(false);
return children({ isOn, toggle: () => setIsOn(v => !v) });
}
// children is a FUNCTION — called with toggle state
<Toggle>
{({ isOn, toggle }) => (
<div>
<button onClick={toggle}>{isOn ? 'ON' : 'OFF'}</button>
{isOn && <p>The toggle is on! 🎉</p>}
</div>
)}
</Toggle>
useToggle() hook is simpler than a <Toggle> render prop component. But render props are
still useful when you need to inject logic into JSX structure, and you'll find them frequently
in pre-Hooks libraries.
8. Composition vs Inheritance — React's Official Stance
Object-oriented programmers often reach for inheritance to share UI logic:
"Let me create a BaseButton class that my
PrimaryButton and DangerButton extend."
React actively discourages this. Here's why — and what to do instead:
// Rigid hierarchy — tight coupling class BaseButton extends Component { renderIcon() { return null; } render() { return ( <button> {this.renderIcon()} {this.props.label} </button> ); } } class IconButton extends BaseButton { renderIcon() { return <span>★</span>; } }
// Flexible — easy to extend function Button({ label, icon, children }) { return ( <button> {icon && <span>{icon}</span>} {label || children} </button> ); } // Compose — no inheritance needed <Button icon="★" label="Favourite" /> <Button> <strong>Bold Text</strong> </Button>
Here is a summary of all the composition patterns covered in this chapter and when to reach for each:
children inside its own structure. Provides the
layout, the caller provides the content.header, footer,
sidebar). Gives parents fine-grained control over
layout sections.
| Pattern | Complexity | Best For | Modern Alternative |
|---|---|---|---|
| Containment (children) | Low | Wrappers, layouts, alerts | — |
| Named Slots | Low | Multi-region layouts | — |
| Compound Components | Medium | Interactive UI groups | — |
| Render Props | Medium | Shared stateful logic | Custom Hooks |
| HOC (Higher-Order Component) | Higher | Cross-cutting concerns | Custom Hooks |
| Inheritance | Avoid in React | Not recommended | Any of the above |
Explore More Tutorials
props.children is React's built-in automatic slot — it
receives whatever JSX is placed between the component's opening and closing tags. Every
component gets it for free without any declaration.
A named slot prop is just a regular prop that happens to hold a JSX value, e.g.
header={<Navbar />}. You define and name it yourself.
It's passed as an attribute on the JSX tag, not between the tags.
When to use which: Use
children for the primary content of
a component. Use named slot props when you need multiple distinct content regions
(header, body, footer) that the wrapper should place in specific positions.
React.cloneElement(element, extraProps) creates a copy of a React element
and merges new props into it. You use it when a parent wrapper needs to inject
extra props into its children without the children declaring those props
themselves.
Classic example — TabGroup: The
<TabGroup /> wrapper
knows which tab is active. It uses React.Children.map + cloneElement to
inject isActive and onClick into each
<Tab /> child — so the parent using <TabGroup>
doesn't need to pass those props manually to every tab.
In modern React, compound components with Context are often preferred over cloneElement because Context works at any depth, not just direct children.
With compound components, the root component provides shared state via React Context. The sub-components consume that context internally, so the caller doesn't need to thread state through every level. The API looks clean and declarative:
<Accordion> <Accordion.Item id="a" title="Q1">Answer</Accordion.Item> </Accordion>
The
<Accordion.Item /> knows which item is open without the caller
passing it — because it reads from the Accordion's Context internally.
1. Props are more flexible than method overriding. Passing
icon={" "} is simpler and more powerful than overriding a
renderIcon() method in a subclass.
2. Composition doesn't create tight coupling. A component that accepts
children or JSX props doesn't need to know anything about the specific
components passed to it. Inheritance creates a fragile base class problem — changes in
the base break all subclasses.
3. Mixins (multi-inheritance) cause conflicts. React tried mixins early on and removed them because of naming collisions and unclear data flow. Custom Hooks solve the same code-sharing problem cleanly.
<Modal />
(self-closing). What is the value of props.children
inside Modal?render prop?<Accordion />
with items that need to know which item is open. What is the cleanest modern approach?
- Composition is React's recommended way to reuse UI logic — combine small components together instead of extending a base class.
props.childrenis the automatic content slot — it holds whatever JSX is placed between the component's opening and closing tags. It can be undefined, a string, a single element, or an array.- The containment pattern uses
childrento build generic wrappers (Modal, Card, Alert) whose content is fully controlled by the parent. - Named slots are regular props holding JSX values — use them when a component needs multiple distinct content regions (header, sidebar, footer).
- The React.Children API provides utilities for working with children:
count,map,forEach,only,toArray. UseReact.cloneElementto inject extra props into children. - Compound components use React Context to share implicit state between a parent and its sub-components — no prop drilling, clean declarative API. Used by React Router, Headless UI, Radix.
- The render props pattern passes a function as a prop; the component calls it with state and renders the result. Useful for sharing logic while keeping UI in the caller's control.
- Custom Hooks are the modern replacement for render props and HOCs — prefer them for sharing stateful logic in new code.
- React explicitly recommends composition over inheritance — props and children provide everything inheritance would offer, with more flexibility and less coupling.
<Accordion />
using the compound components pattern — root provides Context with openId,
Accordion.Item
consumes it. Add 3 FAQ items.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.