0 day streak
javascript / expert
Snippet

Named Slots Pattern via Children Mapping

The 'Named Slots' pattern uses React's Children API to extract specific sub-components. This allows the consumer to define content in any order, while the parent component controls the final layout structure and internal styling.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import React, { Children } from 'react';
const Card = ({ children }) => {
const header = Children.toArray(children).find(
(child) => child.type === Card.Header
);
const body = Children.toArray(children).find(
(child) => child.type === Card.Body
);
return (
<div className="card">
<div className="card-header">{header}</div>
<div className="card-body">{body}</div>
</div>
);
};
Card.Header = ({ children }) => <>{children}</>;
Card.Body = ({ children }) => <>{children}</>;
react
Breakdown
1
Children.toArray(children).find(...)
Searches for a specific component type within the passed children to place it in its designated 'slot'.
2
child.type === Card.Header
Uses the component reference as a unique identifier for identifying sub-parts.
3
Card.Header = ({ children }) => ...
Static properties on the component function serve as semantic markers for layout fragments.