Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 132 ยท Components and Props

Children and Composition

Learn React composition - the children prop, slot props, wrapper and layout components, containment, specialization and passing JSX as props, with live examples.

Most UI frameworks reach for inheritance when they want reuse: a FancyButton extends Button. React takes a different road: composition. You build a component that does not know exactly what it will contain, and the parent fills in the gaps by passing JSX. Components stay small, and you combine them like building blocks instead of stacking them into class hierarchies.

You have already met the children prop in Props. This lesson turns it into a full design toolkit: wrapper components, named slots, layouts, specialization, and the rules about what you can and cannot do with children. Finish it and you will know why React teams almost never need inheritance.

The idea in one example

Imagine a bordered box. A box does not care what sits inside; it only provides a frame. The frame is the component, the contents are passed in.

A frame that holds anything

This is called containment: a component that contains other things it does not know in advance. Dialogs, cards, sidebars, page layouts and tooltips all work this way.

What children actually is

children is whatever you put between the tags, and its shape depends on how much you put:

JSX between the tags children is
nothing (<Frame />) undefined
one string that string
one element one React element object
several nodes an array of them

Because the shape changes, avoid code that assumes children is always an array. Do not write children.length or children.map(...) directly. If you need to inspect or transform children (rare), React provides the Children helpers, covered at the end of this lesson. In the common case you just render and let React sort it out.

The shape of children

The log reads children is undefined, children is string, children is object, children is array of 3 (the bold element, the text " and ", and the italic element are three separate children).

Slots: more than one hole

A component sometimes needs several places that the parent fills: a card has a header, a body and a footer. children can fill only one. The answer is to accept JSX through ordinary props with whatever names you like. Props can hold elements just as well as strings:

Named slots with props

A slot is simply a prop whose value is JSX. Both strings and elements work, because anything React can render may be passed. Optional slots use && to render nothing when absent (watch out for a slot value of 0; see Conditional Rendering). Slots solve the "I need two holes" problem without any special API.

Wrapper and layout components

Composition shines in layouts. A layout component provides structure; pages pass content into it:

A layout component

TwoColumns has no idea there is a navigation or an article. Swap <Navigation /> for something else and nothing in the layout changes. Note that you pass <Navigation /> (an element, already a description of UI), not Navigation (the function). Passing the function would be a different technique (the render prop, see Render Props, HOCs and Hooks).

Specialization: a special case of a general component

Sometimes one component is a particular version of a more general one. In object-oriented languages you might subclass. In React the specific component renders the general one with certain props filled in:

Specialization by rendering the general component

The generic Dialog handles structure and accessibility once; WelcomeDialog and DeleteDialog give it meaning.

Composition tools at a glance

Technique Use it when
children One hole; the content is "everything inside"
Slot props (header, footer, left) Two or more distinct holes
Specialization A component is a configured version of another
Layout components Page structure is repeated across screens
Context (Context) Data must reach deep descendants without threading props

Avoiding prop drilling with composition

Before reaching for context, check whether composition solves your "I am passing this through five layers" problem. If a middle component only forwards a prop to a deep child, let the top build the child and pass the finished element down:

JSX
// Drilling: Page -> Layout -> Sidebar -> UserBadge all carry `user`
<Layout user={user} />

// Composition: Page builds the badge; Layout and Sidebar never see `user`
<Layout sidebar={<UserBadge user={user} />} />

The middle components now only know "I have a sidebar slot". This keeps them reusable and removes the plumbing, with no new React API.

Working with children: use the right tool

Most of the time is enough. When you really must look at what you were given, use the Children helpers from react instead of treating children as an array. Children.toArray flattens the structure, drops null, undefined and booleans, and gives every item a key. Children.count counts what you were given, including null and false entries.

Children.count versus Children.toArray

The list shows three items (first, second, from an array), but the console logs count: 5 toArray length: 3: and count as children even though they render nothing.

The Children helpers are fragile. They only see what the parent wrote directly; if the parent wraps items in its own component (<Group><Item /></Group> where Group renders <Item /> inside a fragment), the helper sees one child, not the items. The official guidance is to avoid Children.map, cloneElement and friends where possible. For components that must coordinate their parts, such as tabs and accordions, use compound components with context instead.

Rules and pitfalls

  • Children are elements, not text templates. You can pass anything renderable, but not plain objects: <Frame>{{ a: 1 }}</Frame> throws Objects are not valid as a React child (found: object with keys {a}). If you meant to render a collection of children, use an array instead.
  • Do not forget to render children. A wrapper component that accepts children but never writes silently swallows its content.
  • Children are created by the parent. In <Frame><Expensive /></Frame> the element <Expensive /> is created when the parent renders. If Frame holds state and re-renders, the children prop is the same object as before, and React can skip re-rendering that part. This "state colocation with children" trick is a real performance tool (memo and Referential Equality).
  • Prefer composition over configuration. Instead of a <Card showFooter footerText="..." footerLink="..." /> with a growing list of flags, expose a footer slot and let callers pass any JSX.
  • Favor slots over inheritance. If you feel the urge to extend a component, ask what part of it varies and make that part a prop.

Here is the "children keep identity" effect in action. The counter component re-renders on every click, but the expensive child, created by the parent, is not re-rendered:

Children passed from above are not re-rendered by the wrapper

On load the console has ClickCounter rendered, count = 0 and Heavy rendered. After each click only ClickCounter rendered, count = ... is added: Heavy is skipped because its element is unchanged. Move <Heavy /> inside ClickCounter's own JSX and it re-renders on every click.

When to use what

  • Use children for the main content area of a wrapper.
  • Use extra slot props when there are two or more regions, or the region is optional and named.
  • Use specialization when many callers need the same configured version of a component.
  • Use context only when composition cannot remove the plumbing, for example data that dozens of unrelated components need.
  • Avoid Children.map/cloneElement for new code; they break as soon as someone wraps an item.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A Card component needs a header region, a body region and a footer region filled by the caller. What is the idiomatic React way?

    Props can hold JSX, so extra regions become slot props while children fills the main one. No inheritance is needed.
  2. 2. What is the type of children in <Box><b>a</b> text</Box>?

    Several children are delivered as an array: here the b element and the text ' text'. With one child you get that child itself.
  3. 3. Given children = [<span/>, null, false, <span/>], what do Children.count(children) and Children.toArray(children).length return?

    Children.count counts null and false entries too (4). toArray drops null, undefined and booleans, leaving 2 elements.
  4. 4. Why does an expensive child passed as children avoid re-rendering when the wrapper's own state changes?

    The wrapper re-renders, but the children prop still points to the same element object created by the parent's last render, so React can skip that subtree.
  5. 5. In <Layout sidebar={<Navigation />} />, what are you passing?

    <Navigation /> evaluates to an element. Passing the function Navigation (without angle brackets) would be a different pattern.

Summary

  • Composition means building UI by combining components and passing JSX in, instead of inheriting from other components.
  • children is whatever sits between the tags; its shape varies (nothing, one node, an array).
  • Extra regions are slot props that hold JSX; layouts and wrappers are plain components with slots.
  • Specialization renders a general component with some props filled in.
  • Passing finished elements from above removes prop drilling and keeps middle components reusable.
  • Avoid Children.map/cloneElement for new code; use context-based compound components for coordinated parts.

Next: Conditional Rendering