DEV Community

Rehan Qadir
Rehan Qadir

Posted on

Nuxt: How to use nuxt-link-active and nuxt-link-exact-active classes with nuxt-link?

Problem

Apply custom active class to active route in nuxt-link tag including all nested routes

Let's say you wish to apply custom active class to an active route in nuxt-link tag.

...
<nav>
    <nuxt-link to="/">Home</nuxt-link>
    <nuxt-link to="/explore">Explore</nuxt-link>
    <nuxt-link to="/about">About</nuxt-link>
</nav>
...
Enter fullscreen mode Exit fullscreen mode

The first choice is to use nuxt-link-active class to style the active route.

.nuxt-link-active {
    font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode
Discrepancy

If user navigates to /explore or /about route, the styling will get applied to / route as well which in practice is not desired.

Well, to resolve this issue one is prompted to use nuxt-link-exact-active along similar lines.

.nuxt-link-exact-active {
    font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode

Apparently this approach resolves the issue very well. But hold on, what if there are some nested routes? What about /explore/express or /explore/ruby-on-rails?

In practice if user navigates to any of the nested routes /explore should continue to have the styling, right? but with just nuxt-link-exact-link class in hand it will fail to persist.

Solution

To get the best of both worlds, use nuxt-link-active class along with exact keyword in nuxt-link tag.

Use exact in the nuxt-link tag

...
<nav>
    <nuxt-link to="/" exact>Home</nuxt-link>
    <nuxt-link to="/explore">Explore</nuxt-link>
    <nuxt-link to="/about" exact>About</nuxt-link>
</nav>
...
Enter fullscreen mode Exit fullscreen mode

with the following css

.nuxt-link-active {
    font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode

For every nested explore routes, /explore will continue to have the styling. Furthermore, / and /about will have the styling only when the exact route matches.


I hope it will help you. Keep coding!

Top comments (4)

Collapse
 
saabbir profile image
Saabbir Hossain

Works. Thanks.

Collapse
 
sigstackfault profile image
Connor King

Doesn't seem to work anymore? nuxt.com/docs/api/components/nuxt-... doesn't show any 'exact' prop and it doesn't seem to work

Collapse
 
ratcat profile image
RatCat

Thanks, its saved my time ;)

Collapse
 
placideirandora profile image
Placide IRANDORA

Thank you for the article! I was facing the activated route styles issue for nested routes. The exact attribute fixed the issue.