<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
Also check Intelligent Navbar