Skip to content

Instantly share code, notes, and snippets.

Last active February 3, 2019 06:37
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save bradfrost/8983ef87f0a236d247f9a8deaf1feefc to your computer and use it in GitHub Desktop.
React component structure
<Breadcrumb text="Home" href="/" />
<Breadcrumb text="Child" href="/child" />
<Breadcrumb text="Grandchild" href="/child/grandchild" />
// or
<Breadcrumbs items={[
text: "Home",
href: "/"
text: "Child",
href: "/child"
text: "Grandchild",
href: "/child/grandchild"
]} />
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.Item {...props} />

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

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 => <Breadcrumb text={item.text} href={item.href} />);

// same thing but shorter/more fancy
const Breadcrumbs = ({ items }) => => <Breadcrumb {...item} />);

Where <Breadcrumb/> can be anything you like, instead of hard-wiring a certain type of element/structure into Breadcrumbs />.

Copy link

jdfm commented Jan 30, 2019

const Breadcrumb = ({ text = 'PLACEHOLDER', href = '#' }) => /* whatever you have now */

const Breadcrumbs = ({ children = Breadcrumb, items }) => <whatever></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. */

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