Highlight Menu Items on Sveltekit

Here is how you can highlight active or current page in the menu on a Sveltekit website.

<script>
  import { page } from "$app/stores";

  const menus = [
    {name: "Home", url: "/"},
    {name: "About", url: "/about"},
    {name: "Blog", url: "/blog"},
  ]

  $: currentPage = $page.url.pathname; //should be reactive
</script>

{#each menus as { url, name }}
  <li>
    <a class:active={url === currentPage}
      href={url}>{name}</a>
  </li>
{/each}

Here is an advanced usage in case you want to highlight /blog even if you are accessing a nested page /blog/a-blog-post

<script>
  import { page } from "$app/stores";

  const menus = [
    {name: "Home", url: "/"},
    {name: "About", url: "/about"},
    {name: "Blog", url: "/blog"},
  ]

  $: currentPage = $page.url.pathname; //should be reactive
</script>

{#each menus as { url, name }}
  <li>
    <a data-sveltekit-prefetch
       class:active={url !== "/"
        ? currentPage.match(url)
        : url === currentPage}
       href={url}>{name}</a>
  </li>
{/each}

You can watch how it is done here

Youtube video:


Also check Intelligent Navbar

Find related articles

Let's discuss on Twitter