Highlighting the current nav entry in your Storyblok/Astro project

Wondering how to indicate in your navigation which page is currently being viewed? Let me show you how it can be done, using the example of the website that you're currently visiting.

Essentially, it is necessary to compare the current slug with the href of the navigation entry. So let's get started.

In Astro, it is rather straightforward to retrieve the current slug. If you use getStaticPaths in a [...slug].astro file, you can get the current slug in any other component by including the following in the front matter:

const { slug } = Astro.params

For the navigation of this website, I decided to create a nav_item component in Storyblok that can be used to dynamically render the navigation. The navigation is implemented in Header.astro like this:

<ul class='flex space-x-4'>
  {story.content.header_nav.map((blok) => {
    return (
        <StoryblokComponent blok={blok} />

In NavItem.astro, which gets rendered automatically through StoryblokComponent, the following code is used:

const { slug } = Astro.params
const { blok } = Astro.props
const url = blok.link.cached_url

const slugToCompare =
  url.charAt(url.length - 1) === '/' ? url.slice(0, -1) : url

  class={slug === slugToCompare ? 'active' : ''}
  href={'/' + blok.link.cached_url}

As you can see, we're first of all getting the current slug as described above. Secondly, we're getting the url of the navigation entry from the component's blok prop. Afterwards, we're making sure to remove any trailing forward slash from the url so that it can be properly compared to the current slug.

Finally, an active class is assigned to the element if the condition is true. And that's it!

Feel free to check out the complete source code of this project.

See all articles