How to Use props.children in React

Building wrapper components like cards and layouts with props.children.

When building React components you'll often want one that wraps other content, like a card, a modal or a page layout. Instead of passing that content in through props, you can nest it between the component's tags the same way you nest HTML. React passes whatever is in between to the component as children.

props.children is whatever you put between a component's opening and closing tags.

Basic Usage

Render children wherever the content should go:

function Card({ children }) {
return <div className="card">{children}</div>
}
function App() {
return (
<Card>
<h2>Hello</h2>
<p>This content is passed in as children.</p>
</Card>
)
}

The rendered HTML is the div with the h2 and p inside it.

Why Not Use Props?

Without children, a card ends up with a prop for every possible piece of content:

<Card
title="Your Account"
text="Signed in as jim@example.com"
buttonText="Sign out"
onButtonClick={signOut}
/>

Every new layout means another prop. With children, Card doesn't need to know what's inside it. It only handles the border, padding and shadow, and you put anything you want inside.

Mixing children with Other Props

children works alongside regular props. A title prop for the header and children for the body is a common pattern:

function Card({ title, children }) {
return (
<div className="card">
<h2 className="card-title">{title}</h2>
<div className="card-body">{children}</div>
</div>
)
}
function Account() {
return (
<Card title="Your Account">
<p>Signed in as jim@example.com</p>
<button onClick={signOut}>Sign out</button>
</Card>
)
}

A Layout Component

The same idea works for a whole page. Wrap each page in a layout that adds the header and footer, using a fragment so there's no extra div:

// components/Layout.js
function Layout({ children }) {
return (
<>
<Header />
<main>{children}</main>
<Footer />
</>
)
}
// pages/about.js
function About() {
return (
<Layout>
<h1>About</h1>
<p>Front-End Web Development Tips.</p>
</Layout>
)
}

If you use Next.js, this is the same pattern as wrapping every page in _app.js.

Whenever a component's job is to wrap something, let the content come in as children.

Have some feedback on this post? .