~/
hackweb.dev
Component Composition
Quiz
⌘K
...
~/
/tutorials
/react/react-component-composition/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/react/10react-component-composition
Write
Preview
Diff
# Component Composition Composition lets you build complex UIs by combining small, reusable pieces. ## The `children` Prop Every component receives `children` — the content between its tags: ```jsx function Card({ children }) { return <div className="card">{children}</div>; } <Card> <h2>Title</h2> <p>Content goes here.</p> </Card> ``` ## Layout Components Wrap shared structure in layout components: ```jsx function PageLayout({ children }) { return ( <div className="layout"> <header>Nav</header> <main>{children}</main> <footer>Footer</footer> </div> ); } <PageLayout> <h1>Home</h1> </PageLayout> ``` ## Slot Pattern Pass specific pieces as named props: ```jsx function Modal({ title, body, footer }) { return ( <div className="modal"> <h2>{title}</h2> <div>{body}</div> <div>{footer}</div> </div> ); } <Modal title="Confirm" body={<p>Are you sure?</p>} footer={<button>OK</button>} /> ``` ## Extracting Reusable Layouts Combine composition with props for flexible patterns: ```jsx function Sidebar({ children, side = "left" }) { return ( <aside className={`sidebar sidebar-${side}`}> {children} </aside> ); } ``` ## Best Practices 1. Favor composition over inheritance 2. Use `children` for generic wrappers 3. Use named props for specific slots 4. Keep layout components simple and presentational ## Common Mistakes 1. Nesting too many layers makes debugging hard 2. Passing everything as `children` loses clarity 3. Forgetting to spread props when needed
No changes yet
Reset to original
Submit suggestion
cancel