Tutorials React JS Children & Composition
Ch 10 / 47
Chapter 10 Beginner–Intermediate 12 min read React JS

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.

Advertisement
What you'll learn
props.children — the automatic slot for nested JSX
Containment pattern — wrapper and layout components
Named slots pattern — passing header, footer and body separately
React.Children API — count, map, forEach, only utilities
Compound components pattern — Context + sub-components
Render props pattern — passing a function as a child
Composition vs Inheritance — React's official recommendation
Composition best practices — when to use each pattern

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.

Core idea Instead of: making a 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.
Reusability
A <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.
DRY
Separation of Concerns
The layout component handles styling and structure. The content component handles what to show. Neither needs to know about the other's internals. Clean, independent, testable.
Clean code
Flexibility
The parent decides what to render; the wrapper decides how it looks. You can swap out the content of a modal, dialog, or sidebar without touching the wrapper at all.
Extensible
Easier Testing
Small composed components are trivial to test in isolation. You don't need complex class hierarchies or mock inheritance chains — just render and assert.
Quality

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.

jsx — Alert.jsx — the simplest use of props.children
// 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>
What type is children? 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.
Self-closing — no children
// children is undefined
<Card />

// Same — children still undefined
<Card></Card>
With content — children populated ✅
// 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.

Modal component — structure provided by component, content by parent
myapp.com/dashboard
<Modal /> — provides overlay, box, close btn
header slot (from parent)
children — any JSX from parent
Modal shell (structural) children (content) footer (named slot)
jsx — Modal.jsx — containment pattern in practice
// ── 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.

Advertisement

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.

jsx — PageLayout.jsx — named slots via JSX props
// ── 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>
  );
}
JSX is just an object In React, JSX compiles to a plain JavaScript object. That means you can pass JSX as a prop value just like any other data. Named slots are nothing special — they're just props whose value happens to be JSX. 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.

React.Children.count(children)
Returns the total number of child elements. Works correctly when children is a single element, an array, or undefined (returns 0).
count → 3
React.Children.map(children, fn)
Maps over children and returns a new array — like Array.map() but handles all child types safely, including null and undefined.
returns array
React.Children.forEach(children, fn)
Iterates over children without returning a new array — for side effects like collecting data. Like Array.forEach().
no return
React.Children.only(children)
Asserts that children contains exactly one React element. Throws an error if zero or more than one child is passed. Use when a component requires a single child.
throws if ≠ 1
React.Children.toArray(children)
Converts children to a flat array with stable keys. Useful for sorting, filtering, or slicing children before rendering.
flat array
React.cloneElement(element, props)
Clones a React element and merges new props into it. Used to inject extra props (like index, isActive, onClick) into children without the parent knowing about them.
new element
jsx — TabGroup.jsx — React.Children.map + cloneElement
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>
jsx — count and only examples
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.

jsx — Accordion.jsx — compound components with Context
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>
Real-world examples of compound components You use compound components every day without noticing: React Router's <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.
⭐⭐⭐⭐⭐
4.9 / 5
🔥 Most Popular at K2infocom · Vadodara
React JS Complete
Masterclass
Composition, Hooks, Context, Router, Redux, REST APIs & 6 real-world projects — guided by experts with live sessions and 100% placement support.
Composition Hooks & Context React Router Redux Toolkit REST APIs 6 Projects Certificate
2,500+Students
6+Projects
3–6Months
100%Placement

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.

jsx — DataFetcher.jsx — render prop for shared fetching logic
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":

jsx — Toggle.jsx — children as render prop (function as child)
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>
Render props vs Hooks today Render props were the go-to pattern before Hooks. Today, custom Hooks replace most render prop use cases with cleaner syntax — a 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:

Inheritance approach ❌
// 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>;
  }
}
Composition approach ✅
// 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:

Containment
A wrapper component renders children inside its own structure. Provides the layout, the caller provides the content.
Use for: Modal, Card, Alert, Tooltip, Sidebar
Named Slots
Multiple JSX regions injected via named props (header, footer, sidebar). Gives parents fine-grained control over layout sections.
Use for: Page layouts, Dashboard shells, Data tables
Compound Components
A parent + child set sharing implicit state via Context. No prop-drilling. Used by major UI libraries. Declarative and expressive API.
Use for: Accordion, Tabs, Select, Dropdown, Stepper
Render Props
A prop (or children) that is a function returning JSX. The component owns the logic; the caller decides the visual output.
Use for: Sharing stateful logic, legacy code, special UI injection
Custom Hooks
The modern replacement for render props and HOCs. Share stateful logic as a reusable hook without wrapping the component tree.
Use for: Most render prop use cases in modern React
React.Children + cloneElement
Inspect, transform, or inject extra props into children. Use when a wrapper needs to enhance direct children without tight coupling.
Use for: Tab groups, Form fields, List items with injected state
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
Advertisement
Knowledge Check — Children & Composition
Q1. What is the difference between props.children and a named slot prop?
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.
Q2. When would you use React.cloneElement?
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.
Q3. What makes compound components different from regular parent/child props?
With regular parent/child props, the parent must explicitly pass state down to each child — which leads to prop drilling or verbose JSX.

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.
Q4. Why does React recommend composition over inheritance?
React's component model is already highly flexible through props and children — inheritance adds unnecessary complexity without adding value. Specifically:

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.
Multiple Choice
MCQ 1
You write <Modal /> (self-closing). What is the value of props.children inside Modal?
MCQ 2
Which React.Children method would you use to enforce that a component receives exactly one child?
MCQ 3
In the render props pattern, what exactly is passed as the render prop?
MCQ 4
You have an <Accordion /> with items that need to know which item is open. What is the cleanest modern approach?
Chapter 10 Summary — Children & Composition
  • Composition is React's recommended way to reuse UI logic — combine small components together instead of extending a base class.
  • props.children is 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 children to 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. Use React.cloneElement to 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.
Practice — Build a Compound Accordion
Open the sandbox. Build an <Accordion /> using the compound components pattern — root provides Context with openId, Accordion.Item consumes it. Add 3 FAQ items.
Open Vite + React Sandbox

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel