How to handle active link with hash and i18n module?
I have i18n module installed, I have two locales, es and ro as fallback. Also in navigation I have a links with hash. So I can't rely on router-link-active because it's always there
2 Replies
Hi @salomon_.. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
To handle active links with hash and i18n module in Nuxt, you can use the
ULink
component from Nuxt UI which provides more control over active link states, especially when working with hash navigation and i18n.
Using ULink Component
The ULink
component from Nuxt UI extends the functionality of NuxtLink
and provides additional props specifically for controlling active states:
The key props to use here are:
- exact-hash
: This will only mark the link as active if the current route hash exactly matches the link's hash
- active-class
: Custom class to apply when the link is active
- inactive-class
: Custom class to apply when the link is inactive
Link component provides these additional controls that aren't available in the standard NuxtLink
.
Without Nuxt UI
If you're not using Nuxt UI, you can create a custom solution by comparing the current route's hash with your link's hash:
Working with i18n
For i18n integration, make sure to use the localePath
function from the i18n module to generate the correct localized paths:
This approach from Stack Overflow shows how to handle language switching while preserving the current URL structure.
Remember that when using Nuxt 3.16.0 or newer with i18n, you should ensure you're using i18n version 9.3 or higher to avoid compatibility issues with the Unhead module as mentioned in this GitHub issue.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@1029431292170874910> Kapa.ai is still learning and improving, please let me know how I did by reacting below.