Menu

Creating partially active links or active trails with React / Gatsby

November 11th, 2019

Ever needed to create active links that belong to a parent link and make sure the parent is still active? In Gatsby you can use the <Link> tag which extends @reach/router. By default you could access the isPartiallyCurrent props. Just make sure there is a /blog page and it's children have an url like /blog/whatever-blog-1. 

 <Link
              getProps={({ isPartiallyCurrent }) =>
                isPartiallyCurrent ? { className: "active" } : null
              }
              to={"/blog}
            >
              Blog
            </Link> 

Custom implementation of active parents

If you need to create some sort of logic however that isn't quite there by default you could just add it in plain Javascript. In @reach/router/index.js there is a prop location in getProps which can be used instead of window.location which breaks the build process of Gatsby.

Link props in React

You now know the current path and you could check if the path has the /blog/ in it's url. If so then you return the className active... 

 const whatLocation = props => {
  const currentLocation = props.pathname
  if (currentLocation.includes("blog")) {
    return { className: "active" }
  }
}

<Link
              to={
                "/blog/another-blog"
              }
              /* @see @reach/router/index.js for location and pass it to the function and return active className if true */
              getProps={({ location }) => whatLocation(location)}
            >
              Another blog
            </Link> 

Happy theming 🤩

Up next: