Components & styles · Lesson 5 of 22 · 10 min
Navigation with active links
Build a Nav component from an array and highlight the current page.
The nav is a list of links. Instead of writing three <a> tags by hand, you’ll keep the links in an array and loop over it. Adding a page later means adding one line.
1. Create Nav.astro
src/components/Nav.astro
---
const links = [
{ label: 'Home', href: '/' },
{ label: 'About', href: '/about' },
{ label: 'Blog', href: '/blog' },
];
const currentPath = Astro.url.pathname;
function isActive(href: string) {
if (href === '/') return currentPath === '/';
return currentPath.startsWith(href);
}
---
<nav aria-label="Main">
<ul>
{links.map((link) => (
<li>
<a
href={link.href}
class:list={{ active: isActive(link.href) }}
aria-current={isActive(link.href) ? 'page' : undefined}
>
{link.label}
</a>
</li>
))}
</ul>
</nav>
What’s new here
Astro.url.pathname is the path of the page being built, like / or /blog/fall-menu.
isActive() checks if a link matches the current page. Home is a special case: every path starts with /, so Home only matches an exact /. Using startsWith for the others means /blog/fall-menu still lights up the Blog link.
class:list is an Astro helper for building class names. { active: true } adds the active class, { active: false } leaves it off. It also accepts strings and arrays:
<a class:list={['link', { active: isActive(link.href) }]}>
aria-current="page" tells screen readers which link is the current page. Setting an attribute to undefined leaves it out of the HTML.
2. Put the Nav in the Header
src/components/Header.astro
---
import Nav from './Nav.astro';
interface Props {
siteName: string;
}
const { siteName } = Astro.props;
---
<header>
<div class="container inner">
<a href="/" class="logo">{siteName}</a>
<Nav />
</div>
</header>
Components can use other components. The homepage doesn’t need to know Nav exists.