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.

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 🤩


Do you have something useful and positive to say about this article?

Up next:

Creating Gatsby pages from Drupal using the same path alias

November 9th, 2019

When looking for a way to decouple your Drupal site Gatsby could be a great choice. It's Open Source and based on React 🚀. Today I'd like to show how to recreate Gatsby pages that have the same url's as Drupal.