More than one hole
children is great when there is one place to put content. But
sometimes a component has several zones you want to fill: a header,
a body, an actions bar... We call those zones slots (holes).
The solution: since in JSX an element is just another value, you can pass JSX
through regular props, not only via children.
function Panel({ title, actions, children }) {
return (
<section className="panel">
<header>{title}</header>
<main>{children}</main>
<footer>{actions}</footer>
</section>
);
}
Each prop is a hole that the caller fills with whatever markup they want:
<Panel
title={<h2>Settings</h2>}
actions={<button>Save</button>}
>
<p>Main content of the panel.</p>
</Panel>
children vs slots via props
- Use
childrenfor the main, single content. - Use slots via props when there are several well-differentiated zones
(
title,actions,icon,footer...).
<ConfirmDialog
title="Delete file?"
cancel={<button>No</button>}
confirm={<button>Yes, delete</button>}
/>
A slot can be any React node: a string, a number, a JSX element or even another already-built component. You decide which
<header>,<aside>or<footer>you place it in.