Passing Children and Composing Components
Passing Children and Composing Components
1. The Special children Prop
In React, when you nest elements inside a component tag, those nested elements are automatically packaged and passed to the component via a reserved prop named children.
This enables component composition, a core architecture design principle in React that allows you to construct flexible, reusable container components without knowing what content will be placed inside them ahead of time.
Consuming the Component:
In this example, the <p> and the <div> are passed into ModalDialog as props.children and rendered inside <div className="modal-body">.
2. Containment vs Specialization
React recommends composition over inheritance. You never need to use object-oriented class inheritance (class SpecialDialog extends Dialog) in React. Instead, you compose components using containment and specialization.
Containment (Generic Shells)
A generic shell doesn't know its children in advance (e.g., Card, Sidebar, Panel):
Specialization (Specific Variants)
Specific components render a generic shell configured with pre-defined props:
3. Multiple Content Slots via Named Props
While children is ideal for the primary body content, sometimes a component needs multiple designated slots (e.g., a header, a body, and an action footer).
You are not restricted to children! You can pass any JSX element or component as a standard named prop:
Practice Quiz
<Panel /> with no content inside, what will props.children evaluate to?children?Introduction to Component State
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Destructuring Props and Default Prop Values | Introduction to Component State |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.