#Is current page active?
4 messages · Page 1 of 1 (latest)
Hi @river stone. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, you can check if the current page is active by using the Astro.url.pathname property. This property gives you the current URL path, which you can then compare with the href of your navigation links to determine if the current page is active.
Here is an example of how you can do this:
const { href, class: className, ...props } = Astro.props;
const isActive = href === Astro.url.pathname.replace(/\/$/, '');
In this example, Astro.url.pathname.replace(/\/$/, '') removes the trailing slash from the current URL path. The isActive variable will be true if the href of the navigation link matches the current URL path, and false otherwise.
This code can be used in the script section of your navigation component. You can then use the isActive variable in the template section of your component to conditionally apply an "active" class to the current navigation link.
Please note that this solution assumes that the href of your navigation links do not have a trailing slash. If they do, you might need to remove the trailing slash from the href as well before comparing it with the current URL path.
You can find more information about this in the Astro GitHub issue (https://github.com/withastro/astro/issues/5248) where this solution was discussed.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@river stone kapa.ai is still learning and improving, please let us know how it did by reacting below