#Creating a navigation bar that determines active state
4 messages · Page 1 of 1 (latest)
Hi @uncut gull. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To create a navigation bar component in Astro that determines the active page, you can follow these steps:
- Create a Navigation Component: Create a new file named
Navigation.astroin thesrc/components/directory. In this file, you can add your navigation links. For example:
<a href="/">Home</a>
<a href="/about/">About</a>
<a href="/blog/">Blog</a>
(Source: Astro Documentation (https://docs.astro.build/en/tutorial/3-components/1#_top))
- Import and Use the Navigation Component: Import the
Navigation.astrocomponent in your page file (e.g.,index.astro) and replace the existing navigation HTML link elements with the new navigation component you just imported. For example:
---import Navigation from '../components/Navigation.astro';---
<a href="/">Home</a>
<a href="/about/">About</a>
<a href="/blog/">Blog</a>
<Navigation />
(Source: Astro Documentation (https://docs.astro.build/en/tutorial/3-components/1#_top))
- Determine the Active Page: To highlight the active page link in the navigation bar, you can use the
Astro.url.pathnameproperty to get the current page's path. Then, you can compare this path with thehrefattribute of each link to determine if it's the active page. For example:
const { href, class: className, ...props } = Astro.props;
const isActive = href === Astro.url.pathname.replace(/\/$/, '');
(Source: Github Issue (https://github.com/withastro/astro/issues/5248))
Please note that the above code removes the trailing slash from the current page's path before comparing it with the href attribute. This works for all routes except the index route. For the index route, you might need to add a special case to handle it. For example:
let pathnameWithoutTrailingSlash = Astro.url.pathname.replace(/\/$/, '');
if (href === "/" && pathnameWithoutTrailingSlash === "") {
pathnameWithoutTrailingSlash = "/";
}
const isActive = href === pathnameWithoutTrailingSlash;
(Source: Github Issue (https://github.com/withastro/astro/issues/5248))
- Highlight the Active Link: If a link is the active page, you can add a special CSS class to it to highlight it. The exact way to do this depends on how you're styling your components.