Sveltekit: Styling active links with $page.path

Viewed 2117

I'm working on a sveltekit app with a sidenav containing links. I can't get the active class styling on my links to work properly.

The links are components in NavLink.svelte:

<script>
  import { page } from '$app/stores';
  import Icon from '$lib/Icon.svelte';
  export let title;
  export let href;
</script>

<a {href} class="link" class:active={$page.path == href}>
  <Icon {title} />
</a>

<style>
a.active {
  background-color: rgba(0,0,0,0.24);
</style>

These links are used in SideNav.svelte:

<script>
  import NavLink from '$lib/NavLink.svelte';
</script>

<nav class="container">
  <div id="links">
    <NavLink href="/link1" title="icon1" />
    <NavLink href="/link2" title="icon2" />
    <NavLink href="/link3" title="icon3" />
  </div>
</nav>

And finally, the sidenav is loaded in my __layout.svelte:

<SideNav />
<slot />
<Footer />

Now when I click one of my sidenav links, I am routed to the proper page but my NavLink is not styled with the .active class. If I inspect the link, however, devtools shows me this: <a class="link active:true"> and the other links have active:false.

So it looks like the function is working, but my active style is not applied (the background color). What am I missing?

I tried moving the Active class code to the SideNav component instead of the NavLink component and observed the same behavior. I could not figure it out, so I found a new method that works just fine.

In my NavLink.svelte:

<script>
  import {onMount} from "svelte";
  import Icon from '$lib/Icon.svelte';

  let currentPath;
  onMount(() => {
    currentPath = window.location.pathname;
  });
  export let title;
  export let href;
</script>

<a {href} class:active={currentPath == href}>
  <Icon {title} />
</a>

And the rest of the code is the same. Now my links get the proper styling. It's worth noting that they simply have <a class="active"> and not <a class="active:true">. Why wasn't it working with the other method?

1 Answers

I figured it out.... I think I just forgot to include quotes. D'oh. Working code (that also accounts for sub-pages) for the NavLink is:

<a {href} class:active="{$page.path.includes(href)}">

Related