0
0
ReactHow-ToBeginner · 3 min read

How to Use Component Composition in React: Simple Guide

In React, component composition means building components by combining smaller components inside them. You use props.children or pass components as props to nest and reuse UI parts easily.
📐

Syntax

Component composition in React uses props.children to nest components or passes components as props to include them inside others.

props.children holds any nested elements inside a component tag.

You can also pass components as props to control what renders inside.

jsx
function Container({ children }) {
  return <div className="container">{children}</div>;
}

function Page() {
  return (
    <Container>
      <h1>Welcome</h1>
      <p>This is inside the container.</p>
    </Container>
  );
}
Output
A div with class 'container' wrapping an h1 and a paragraph.
💻

Example

This example shows a Card component that uses props.children to wrap any content inside a styled box. It also shows passing a footer prop to customize the card's footer area.

jsx
import React from 'react';

function Card({ children, footer }) {
  return (
    <div style={{ border: '1px solid #ccc', padding: '1rem', borderRadius: '8px' }}>
      <div>{children}</div>
      {footer && <div style={{ marginTop: '1rem', fontSize: '0.9rem', color: '#555' }}>{footer}</div>}
    </div>
  );
}

function App() {
  return (
    <Card footer={<button>Click me</button>}>
      <h2>Card Title</h2>
      <p>This is some card content.</p>
    </Card>
  );
}

export default App;
Output
A styled box showing 'Card Title' and 'This is some card content.' with a button labeled 'Click me' below.
⚠️

Common Pitfalls

  • Forgetting to use props.children inside the parent component will cause nested content not to render.
  • Passing components incorrectly as props (e.g., passing a component type instead of an element) can cause errors.
  • Overusing composition can make code hard to follow if components become deeply nested.
jsx
function Wrapper({ children }) {
  // Wrong: missing {children} means nested content won't show
  return <div className="wrapper"></div>;
}

// Correct way:
function WrapperCorrect({ children }) {
  return <div className="wrapper">{children}</div>;
}
📊

Quick Reference

  • props.children: Use to render nested content inside a component.
  • Passing components as props: Pass JSX elements or functions to customize parts of a component.
  • Keep components focused: Compose small components for better reuse and clarity.

Key Takeaways

Use props.children to nest content inside components easily.
Pass components as props to customize parts of a component.
Always render props.children inside your component to show nested content.
Keep components small and focused for better composition and reuse.
Avoid deep nesting to keep your UI code simple and readable.