-
-
Save bradfrost/8983ef87f0a236d247f9a8deaf1feefc to your computer and use it in GitHub Desktop.
<Breadcrumbs> | |
<Breadcrumb text="Home" href="/" /> | |
<Breadcrumb text="Child" href="/child" /> | |
<Breadcrumb text="Grandchild" href="/child/grandchild" /> | |
</Breadcrumbs> | |
// or | |
<Breadcrumbs items={[ | |
{ | |
text: "Home", | |
href: "/" | |
}, | |
{ | |
text: "Child", | |
href: "/child" | |
}, | |
{ | |
text: "Grandchild", | |
href: "/child/grandchild" | |
} | |
]} /> |
1st approach is only really viable (and totally ok in that case, imo) if you have a small amount of static data that you'll only update manually every once in a while. Once the amount of items increases or they start changing more often (perhaps through dynamic data from some endpoint, a CMS or or whatnot), you'll want to switch to approach #2.
You can also combine both approaches (#1, pulling parts out of your wrapper component and #2, looping over them programatically) if that helps reduce repetition, like so:
const Breadcrumbs = props => {
return props.items.map(item => <Breadcrumb text={item.text} href={item.href} />);
}
// same thing but shorter/more fancy
const Breadcrumbs = ({ items }) => items.map(item => <Breadcrumb {...item} />);
Where <Breadcrumb/>
can be anything you like, instead of hard-wiring a certain type of element/structure into Breadcrumbs />
.
const Breadcrumb = ({ text = 'PLACEHOLDER', href = '#' }) => /* whatever you have now */
const Breadcrumbs = ({ children = Breadcrumb, items }) => <whatever>items.map(children)</whatever>
This can be used like:
<Breadcrumbs items={data} />
Or, if you don't like the default guts of it:
<Breadcrumbs items={data}>
({ text, href }) => /* Whatever JSX you want, but different from default. */
</Breadcrumbs>
Not limited to the same data structure (still breadcrumbs, but using different kind of data?).
Not sure how the community feels about this though. Thoughts?
For this pattern, I like to assign components as properties on the main component. Like this:
Then you can use it like this:
This is nice because then it’s very clear that the sub component should only be used within its parent.