AI Hints
Home›React Tutorial›TypeScript and Patterns
React · Lesson 62 of 120

Composition

Components inside components.

⏱ 2 min read▶ Video at 51:33🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Instead of one big component with lots of options, React code tends to compose small ones. A component can accept other components, as children or as props.

  • Not one big component
  • Compose small ones
  • Children and props

A flexible card

Card doesn't know what goes inside it. It takes a title, a footer, and children. App fills it with a description and a price tag. Composing small components like this beats one big component with many options. Run it.

App.jsxjsx
function Card({ title, footer, children }) {
  return (
    <div className="box">
      <h2>{title}</h2>
      {children}
      {footer && <p style={{ color: "#555" }}>{footer}</p>}
    </div>
  );
}
function PriceTag({ price }) {
  return <b>£{price.toFixed(2)}</b>;
}
export default function App() {
  return (
    <Card title="Trail 500" footer="Free delivery">
      <p>A tough mountain bike.</p> <PriceTag price={849.5} />
    </Card>
  );
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}

Why compose

Each small component is easy to understand and test. Callers decide what goes inside. And you avoid long lists of true or false props, that try to cover every case.

keyvalue
Smalleasy to test
Callerschoose the content
Avoidmany boolean props
Toolchildren

Summary

Compose small components, passing content in as children or props. Next, lists with filters.

Key takeaways
  • children
  • Small pieces
  • Flexible
Next up: Lists with Filters — a search box