Composition Component Composition

Last updated: 2026-11-02

Composition Component Composition

React recommends composition rather than inheritance for reusing components: the parent passes JSX in as children or as a custom prop, a generic container such as Card, Layout or Modal decides where that JSX goes, and the caller decides what it contains. Children is therefore the most natural slot mechanism of them all. The container stays ignorant of the content it renders, so the same frame can host a form, a chart or a paragraph without ever knowing which one it is showing.

GroupComponent Patterns
KindPattern

ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.

📝 Syntax

function Card({ children, footer }) {
  return (
    <div className="card">
      <div>{children}</div>   {/* the main content slot */}
      <div>{footer}</div>     {/* a custom slot prop */}
    </div>
  )
}

// usage: <Card footer={<small>2026</small>}><p>Body text</p></Card>

Returns:No return value; this entry describes an encoding pattern rather than a function.

▶ Example

The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.

Output:

Two titled card panels whose content is supplied by the caller through children — Panel only owns the frame and never cares about the structure inside.

💡 Key Points

💡 Tip props.children is the implicit slot; when you need several slots, pass JSX through named props such as header and footer.
ℹ️ Info Composition keeps a container independent from its content: Panel neither knows nor cares what goes inside, so the two are decoupled by nature.
⚠️ Warning Do not use cloneElement or class inheritance to inject structure — in the vast majority of cases children plus props is clearer and easier to control.
More case studies coming soon.

📚 Related Tutorials

❓ FAQ

Q What is the difference between children and an ordinary prop?
A Children is the content between the opening and closing tags, which feels more natural in JSX syntax; under the hood it is still a prop and can be mixed with named props freely.
Q How do I implement several slots?
A Define several JSX-typed props — <Modal header={…} footer={…}>{body}</Modal> — and render each of them inside the component.
Q Why choose composition over inheritance?
A React's official stance: inheritance couples a component to the implementation of its parent class, while composition passes JSX through props, which is flexible, predictable and needs no class syntax.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏