Course contentsShow
← React
Lesson 255 of 2,3968. Props PatternsFree lesson

Cloning Children with cloneElement

Using React.cloneElement to inject props into children elements, enabling parent-child coordination patterns.

Cloning Children with cloneElement

You'll learn how to use React.cloneElement to inject additional props into child components that are passed through the children prop.

The Problem: Children Are Opaque

When a component receives children, those elements are already created. You can't directly modify them or add props to them. But sometimes you need to coordinate with children — passing down shared state, event handlers, or configuration that the child needs to work properly.

The Solution: cloneElement

React.cloneElement creates a copy of a child element with new props merged in. Think of it like photocopying a document and adding sticky notes to the copy — the original stays unchanged, but your copy has extra information.

Basic syntax:

React.cloneElement(element, additionalProps)

Practical Example

A Tabs component that needs to tell each child tab whether it's active:

function Tabs({ activeIndex, children }) {
  return (
    <div className="tabs">
      {React.Children.map(children, (child, index) => {
        return React.cloneElement(child, {
          isActive: index === activeIndex
        });
      })}
    </div>
  );
}

function Tab({ isActive, children }) {
  return (
    <div className={isActive ? 'tab-active' : 'tab'}>
      {children}
    </div>
  );
}

The parent coordinates the active state, and each Tab receives the isActive prop automatically — even though the parent's user didn't explicitly pass it.

When to Use This Pattern

This pattern shines for wrapper components that manage shared behavior (tabs, accordions, form field wrappers). The parent "injects" coordination props into children that need to work together.

Key Takeaway: React.cloneElement lets parent components inject props into their children, enabling powerful coordination patterns where the parent controls shared behavior across multiple child elements.