Children & Composition

Easy

Composition is React's primary pattern for building complex UIs from simple components. The children prop lets components wrap arbitrary content without knowing what that content will be, enabling flexible and reusable layouts.

Interactive Visualization

Key Points

  • children is a special prop containing nested JSX elements
  • Composition is preferred over inheritance in React
  • Components can accept render functions as children for flexibility
  • ReactNode type covers all valid children values
  • Slot patterns use named props for multiple content areas
  • Composition keeps components focused and reusable

Code Examples

Basic Composition with children

import { ReactNode } from 'react'

interface CardProps {
  title: string
  children: ReactNode
}

function Card({ title, children }: CardProps) {
  return (
    <div className="card">
      <h2>{title}</h2>
      <div className="card-body">{children}</div>
    </div>
  )
}

function App() {
  return (
    <Card title="Profile">
      <img src="/avatar.png" alt="avatar" />
      <p>Hello, world!</p>
    </Card>
  )
}

The Card component wraps any content passed as children, making it reusable for different layouts

Slot Pattern with Named Props

import { ReactNode } from 'react'

interface PageLayoutProps {
  header: ReactNode
  sidebar: ReactNode
  children: ReactNode
}

function PageLayout({ header, sidebar, children }: PageLayoutProps) {
  return (
    <div className="layout">
      <header>{header}</header>
      <aside>{sidebar}</aside>
      <main>{children}</main>
    </div>
  )
}

function Dashboard() {
  return (
    <PageLayout
      header={<NavBar />}
      sidebar={<FilterPanel />}
    >
      <DataGrid />
    </PageLayout>
  )
}

Named props act as slots for multiple content areas, giving consumers full control over each section

Common Mistakes

  • Using inheritance to share behavior between components instead of composition
  • Typing children as JSX.Element instead of ReactNode which excludes strings and numbers
  • Creating monolithic components instead of composing smaller ones

Interview Tips

  • Explain why React favors composition over inheritance
  • Give examples of the slot pattern for complex layouts
  • Discuss how children composition relates to the open-closed principle

Related Concepts