Composition: The Art of Nesting Components Inside Each Other

In modern React, we almost never use classes. We write components as functions. It's simpler, faster, and more predictable. But how do we assemble a huge site from simple functions? With Composition.

1. Forgetting Inheritance

In regular programming (OOP), they often say: " Let PaymentButton inherit properties from RegularButton. " In React, we don't do that. Instead, we take RegularButton and put it inside PaymentButton. This is composition.

2. Analogy: Matryoshka Doll

You open a large matryoshka (App), inside lies a smaller matryoshka (Page), inside it — an even smaller one (Section), and at the very end — a tiny one (Button). Each component is just a shell for what lies inside.

3. The children Prop: The Magic Window

The most powerful composition tool is a special prop called children. It allows you to create a " frame " component, into which you'll insert content later.

Imagine a photo frame (Card): The frame doesn't care whose photo you insert into it. Its job is simply to draw beautiful edges and a background.

function Card({ children }) {
  return (
    <div className="border-shadow p-4 rounded-lg">
      {/* Everything you write between <Card>...</Card> tags will end up here */}
      {children}
    </div>
  );
}

// Now we can use Card for anything:
<Card>
  <h1>This is a header</h1>
  <p>And some text inside the frame</p>
</Card>

<Card>
  <img src="avatar.jpg" />
  <button>Profile</button>
</Card>

4. Why Do We Need This?

  1. Flexibility: The same Layout component can handle the overall site structure (header, menu, footer), and you'll change the central part (children) on each page.
  2. Cleanliness: You don't need to pass 50 props into a component. You simply " thread " ready-made interface pieces inside the shell.
  3. Logic separate, Visuals separate: You can create a FadeInAnimation component that simply smoothly " reveals " whatever lies in its children. Now you can animate any part of the site just by wrapping it in this component.

*Remember: In React, you don't build a hierarchy of " who descended from whom. " You build a structure of " who is nested inside whom. " *