guus van de wal
Menu

Creating partially active links or active trails with React / Gatsby

1 January 2024
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 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. 

Code Syntax Block tsx

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

Image of build process 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... 

Code Syntax Block tsx

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 🤩