title: Sveltekit: Styling active links with $page.path
body: <p>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.</p>
  <p>The links are components in <strong>NavLink.svelte</strong>:</p>
  <pre><code>&lt;script&gt;
    import { page } from '$app/stores';
    import Icon from '$lib/Icon.svelte';
    export let title;
    export let href;
  &lt;/script&gt;
  
  &lt;a {href} class=&quot;link&quot; class:active={$page.path == href}&gt;
    &lt;Icon {title} /&gt;
  &lt;/a&gt;
  
  &lt;style&gt;
  a.active {
    background-color: rgba(0,0,0,0.24);
  &lt;/style&gt;
  </code></pre>
  <p>These links are used in <strong>SideNav.svelte</strong>:</p>
  <pre><code>&lt;script&gt;
    import NavLink from '$lib/NavLink.svelte';
  &lt;/script&gt;
  
  &lt;nav class=&quot;container&quot;&gt;
    &lt;div id=&quot;links&quot;&gt;
      &lt;NavLink href=&quot;/link1&quot; title=&quot;icon1&quot; /&gt;
      &lt;NavLink href=&quot;/link2&quot; title=&quot;icon2&quot; /&gt;
      &lt;NavLink href=&quot;/link3&quot; title=&quot;icon3&quot; /&gt;
    &lt;/div&gt;
  &lt;/nav&gt;
  </code></pre>
  <p>And finally, the sidenav is loaded in my <strong>__layout.svelte</strong>:</p>
  <pre><code>&lt;SideNav /&gt;
  &lt;slot /&gt;
  &lt;Footer /&gt;
  </code></pre>
  <p>Now when I click one of my sidenav links, I am routed to the proper page but my NavLink is not styled with the <code>.active</code> class. If I inspect the link, however, devtools shows me this: <code>&lt;a class=&quot;link active:true&quot;&gt;</code> and the other links have <code>active:false</code>.</p>
  <p>So it looks like the function is working, but my active style is not applied (the background color). What am I missing?</p>
  <p>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.</p>
  <p>In my <strong>NavLink.svelte</strong>:</p>
  <pre><code>&lt;script&gt;
    import {onMount} from &quot;svelte&quot;;
    import Icon from '$lib/Icon.svelte';
  
    let currentPath;
    onMount(() =&gt; {
      currentPath = window.location.pathname;
    });
    export let title;
    export let href;
  &lt;/script&gt;
  
  &lt;a {href} class:active={currentPath == href}&gt;
    &lt;Icon {title} /&gt;
  &lt;/a&gt;
  </code></pre>
  <p>And the rest of the code is the same. Now my links get the proper styling. It's worth noting that they simply have <code>&lt;a class=&quot;active&quot;&gt;</code> and not <code>&lt;a class=&quot;active:true&quot;&gt;</code>. Why wasn't it working with the other method?</p>