Skip to content

Instantly share code, notes, and snippets.

@bradfrost
Last active February 3, 2019 06:37
Show Gist options
  • Save bradfrost/8983ef87f0a236d247f9a8deaf1feefc to your computer and use it in GitHub Desktop.
Save bradfrost/8983ef87f0a236d247f9a8deaf1feefc to your computer and use it in GitHub Desktop.
React component structure
<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"
}
]} />
@chasemccoy
Copy link

For this pattern, I like to assign components as properties on the main component. Like this:

Breadcrumb.Item = <Component />

Then you can use it like this:

<Breadcrumb>
  <Breadcrumb.Item {...props} />
</Breadcrumb>

This is nice because then it’s very clear that the sub component should only be used within its parent.

@jpkempf
Copy link

jpkempf commented Jan 30, 2019

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 />.

@jdfm
Copy link

jdfm commented Jan 30, 2019

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment