iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Children Prop

The children prop is whatever JSX you put between a component’s opening and closing tags. It’s the foundation of composition — layouts, slots, and reusable wrappers all flow from children.

children, function-as-children, slots

EXAMPLE
// 1) Passthrough wrapper
function Card({ children, title }) {
    return (
        <div className="card">
            <h3>{title}</h3>
            <div className="card-body">{children}</div>
        </div>
    );
}

<Card title="Hello">
    <p>Anything that lives between the tags lands in children.</p>
    <button>Click me</button>
</Card>

// 2) Render prop / function-as-children — total control
function Toggle({ children }) {
    const [on, setOn] = useState(false);
    return children({ on, toggle: () => setOn(!on) });
}

<Toggle>
    {({ on, toggle }) => (
        <button onClick={toggle}>{on ? 'ON' : 'OFF'}</button>
    )}
</Toggle>

// 3) Named slots via props (the React way — there's no <slot/>)
function Page({ header, sidebar, children, footer }) {
    return (
        <div className="page">
            <header>{header}</header>
            <div className="main">
                <aside>{sidebar}</aside>
                <main>{children}</main>
            </div>
            <footer>{footer}</footer>
        </div>
    );
}

<Page
    header={<TopNav />}
    sidebar={<Filters />}
    footer={<Copyright />}
>
    <Results />
</Page>

// 4) React.Children — iterate / clone (rarely needed; usually a map works)
import { Children, cloneElement } from 'react';

function Stack({ children, gap = 8 }) {
    return Children.map(children, (child, i) => (
        <div style={{ marginTop: i === 0 ? 0 : gap }}>{child}</div>
    ));
}

// 5) Counting / asserting children
function TwoCol({ children }) {
    const items = Children.toArray(children);
    if (items.length !== 2) throw new Error('TwoCol needs exactly 2 children');
    return <div className="row"><div>{items[0]}</div><div>{items[1]}</div></div>;
}

Why it matters

Composition with children kills prop-bloat. Instead of <Modal hasHeader title="..." ctaLabel="OK" ...>, you just put the markup INSIDE the modal — readable, flexible, type-safe.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
function Card({ children }) {
    return <section className="card">{children}</section>;
}
// <Card><p>Hello</p></Card>
Try it Yourself »

Discussion

Loading…