Link Components and Active States
What you'll learn: How to create navigation links that feel instant and automatically highlight the current page, without full browser reloads.
Why Regular Links Need an Upgrade
When you click a regular <a href="/about"> link, the browser performs a full page reload. For single-page applications (SPAs) using client-side routing, this defeats the purpose! Instead, you need link components that intercept clicks and use the History API to navigate smoothly—like switching channels on your TV without turning it off and back on.
Creating Click-Intercepting Links
Your link component prevents default navigation and uses history.pushState() instead:
// Intercept all link clicks
document.addEventListener('click', (e) => {
if (e.target.matches('a[href^="/"]')) {
e.preventDefault();
const url = e.target.getAttribute('href');
history.pushState(null, '', url);
// Trigger your route rendering logic
renderRoute(url);
}
});
This makes navigation instant while updating the URL bar.
Active State Highlighting
The second half of the pattern is showing which page is active. Compare window.location.pathname to each link's href:
function updateActiveLinks() {
const currentPath = window.location.pathname;
document.querySelectorAll('nav a').forEach(link => {
if (link.getAttribute('href') === currentPath) {
link.classList.add('active');
} else {
link.classList.remove('active');
}
});
}
// Run after every navigation
window.addEventListener('popstate', updateActiveLinks);
Now your navigation menu always reflects where the user is, providing critical visual feedback.
When to Update Active States
Call your active-state function after pushState(), replaceState(), and during popstate events. This ensures the highlight stays accurate whether users click links or use browser buttons.
Key Takeaway: Link components intercept clicks to prevent reloads and use the History API for instant navigation, while active state logic highlights the current route by comparing URLs and toggling CSS classes.