Sub topic 10
Props as slots
A slot is a prop that accepts a piece of UI, so the parent decides what goes in each region of a component. This chapter assumes you know function components, props, JSX, and the children prop, and that you have seen composition with children earlier in this tutorial.
What a slot is
children gives a component one open region. Many components need several: a card has a header, a body, and a footer, and a page has a sidebar and a main area. A slot prop works like children with a name. You pass a React element, or any renderable value, through a prop, and the component places it.
export function Card({ media, header, footer, children }) {
return (
<article className="card">
{media ? <div className="card-media">{media}</div> : null}
{header ? <header className="card-header">{header}</header> : null}
<div className="card-body">{children}</div>
{footer ? <footer className="card-footer">{footer}</footer> : null}
</article>
);
}The consumer fills only the slots it needs:
import { Card } from './Card';
export function ProfileCard({ user }) {
return (
<Card
header={<h2>{user.name}</h2>}
footer={<button type="button">Follow</button>}
>
<p>{user.bio}</p>
</Card>
);
}Card owns the structure, spacing, and wrapper elements. ProfileCard owns the content. Card never needs to know that the footer holds a button.
Why use slots
- The layout stays fixed while the content varies. Spacing and semantic elements such as
headerandfooterare written once. - There is no prop explosion. Compare
<Card title="..." footerButtonLabel="..." onFooterButtonClick={...} />with afooterslot. Every new need would otherwise add another prop. - State stays with the consumer. The slot element is created in the parent's render, so a button in the footer can use the parent's state and handlers directly.
- It is simple. There is no context, no static properties, and no
Childrenutilities.
Rendering optional slots
Wrap each optional region in a condition. Otherwise an empty <footer> still appears and its padding or border shows up in the layout.
A plain truthiness check has a gotcha. In React, 0 is a valid renderable value, but 0 ? ... : null skips it. Empty strings behave the same way. If a slot might receive a number, test explicitly:
function hasContent(node) {
return node !== null && node !== undefined && node !== false && node !== '';
}
export function Panel({ title, actions, children }) {
return (
<section>
{hasContent(title) && <h3>{title}</h3>}
<div>{children}</div>
{hasContent(actions) && <div className="actions">{actions}</div>}
</section>
);
}true is also never rendered by React, but a slot value of true is almost always a mistake. Treating it as empty is usually fine.
Slots that receive data
Sometimes a slot needs values that only the component knows, such as a close function or the current item. In that case the slot is a function, which is the render prop pattern applied to a named region.
import { useState } from 'react';
export function Disclosure({ summary, children, footer }) {
const [open, setOpen] = useState(false);
const close = () => setOpen(false);
return (
<div>
<button type="button" aria-expanded={open} onClick={() => setOpen((o) => !o)}>
{summary}
</button>
{open && (
<div>
{children}
{typeof footer === 'function' ? footer({ close }) : footer}
</div>
)}
</div>
);
}
export function Example() {
return (
<Disclosure
summary="Details"
footer={({ close }) => (
<button type="button" onClick={close}>Done</button>
)}
>
<p>Hidden until opened.</p>
</Disclosure>
);
}Accepting both a node and a function, as footer does here, is convenient but makes the prop's type less obvious. Pick one form per slot, and document it, unless you have a reason to support both.
Elements or components as slot values
A slot prop can hold an element (icon={<SearchIcon />}) or a component (Icon={SearchIcon}). The two have different consequences.
| Approach | Example | Strength | Cost |
|---|---|---|---|
| Element | `icon={<SearchIcon size={16} />}` | Consumer sets props directly. Simple to read. | Component cannot add props such as size or color. |
| Component | `Icon={SearchIcon}` | Component renders `<Icon size={16} />` with its own props. | Consumer must wrap to pass extra props. The prop name must be capitalized. |
Use elements by default. Use a component prop when the host needs to inject props, such as a design system that sets icon size from a size variant.
Never define the slot component inline during render and pass it as a component prop. A new function identity on each render makes React unmount and remount the subtree, which destroys its state:
// Avoid: a new component type is created on every render of Parent.
function Parent() {
return <List Row={({ item }) => <li>{item}</li>} items={['a', 'b']} />;
}Define the component outside Parent, or pass an element or a render function instead.
Slots compared with compound components
Both let the consumer control the markup. They differ in who controls placement and shared state.
| Question | Slots | Compound components |
|---|---|---|
| Where does content go? | In fixed regions the parent chooses. | Wherever the consumer places subcomponents. |
| Can the consumer reorder parts? | No. | Yes. |
| How do parts share state? | They do not. The parent passes data only through function slots. | Through context. |
| Cost to build | A few props. | Context, a guard hook, and static properties. |
If the layout is fixed and the parts do not need to coordinate, slots are enough. If the consumer must reorder parts, wrap them in extra markup, or place them at different depths, as in Tabs earlier, use compound components.
Edge cases and pitfalls
- Slots are created every render. Elements passed as props are new objects each time the parent renders. A
React.memochild that receivesheader={<h2>...</h2>}will re-render, because the prop is never referentially equal. Memoize the element withuseMemoonly after you have measured a problem. - Fragments and arrays. A slot can hold a fragment or an array, but an array needs
keyprops on its items. Use a fragment when you want several siblings in one slot. - Accessibility is the consumer's job.
Cardcan supplyheaderandfooterlandmarks, but it cannot check that the slot content contains a real heading. Document what each slot expects. - Names matter. Name slots after their purpose (
footer,actions,media), not their position (left,top), so the name still fits if the layout changes.
Exercise
A Layout component takes sidebar and children. A teammate passes sidebar={count} where count is 0, and the sidebar region does not appear. The component uses {sidebar ? <aside>{sidebar}</aside> : null}. What is the cause, and how do you fix it?
Show answer
0 is falsy, so the conditional treats it as "no slot", even though React could render it as the text "0". Replace the truthiness check with an explicit test, such as sidebar !== null && sidebar !== undefined && sidebar !== false && sidebar !== '', so only truly empty values are skipped.
Exercise
You write <List Row={({ item }) => <li>{item}</li>} /> inside a parent that re-renders often, and rows lose their internal state. Why does this happen, and what are two ways to avoid it?
Show answer
The inline arrow function is a new component type on every parent render, so React unmounts the old rows and mounts new ones. Either define the row component outside the parent and pass that stable reference, or pass an element or a render function (renderRow={(item) => <li>{item}</li>}) so React is not asked to treat it as a component type.