Building your own Gatsby breadcrumb component

Date: Wednesday April 8th, 2020


Gatsy Breadcrumbs


Why do people need breadcrumbs on their website? Whilst they used to be a staple of websites, in today’s age they are more optional than paramount, however they are still highly useful for easy navigation, accessibility and user experience

Install the breadcrumb component

First things first we need to install the gatsby breadcrumb

npm install gatsby-plugin-breadcrumb

Installing this allows us to access the location from pagecontext. Install in the gatsby-config like so

{
  resolve: `gatsby-plugin-breadcrumb`,
  options: {
    useAutoGen: true,
 },
},

Now our custom component


Honestly I couldn't get on with the default autogen or click tracking options and components that came with the package. Click tracking kept adding in superfluous links and autogen never quite hit the spot, so I built my own

The build


const juicyBread = ({ breaddata }) => {
   var elementsNew = []

   breaddata.crumbs.forEach(createdBread);
   function createdBread(item) {
    var newlast = item.crumbLabel.replace(/-/g, " ");
    elementsNew.push({pathname: item.pathname, crumlabel: newlast});
  }
  //console.log(elementsNew)


  return (

    <>
    <div className="row">
    <div className="col-md-12 shopintro">
<ul className="gjbread">
    {elementsNew.map((value, index) => {
      return  <li key={index} className="gjbreadcrumb"> 
      <Link key={index} to={`${value.pathname}`}>{value.crumlabel} <span> / </span> </Link>
      </li>
    })}
  </ul>
</div>
</div>
</>
  )
}

export default juicyBread

The build


What are we doing? we're taking the object we passed into the breadcrum component, iterating over it and display it on the screen with it's link.

Passing data as so

<Bread breaddata={pageContext.breadcrumb} ></Bread>

You can get more info on the breadcrum data passed through here

https://www.gatsbyjs.org/packages/gatsby-plugin-breadcrumb/

Back to News

info@getjuicy.co.uk

01245 476077

7B4 Kingsburys House
Fridays Cross Mews
Christchurch Road
Ringwood
BH24 1DG