I am working on a site with SvelteKit and I want to have a layout with a navbar for each page. The navbar has links with the active link being the page you are on. Is there a way I can pass a prop from each page to the template that changes which link is active?
Thanks!
I think I know what you're looking for. SvelteKit comes with the default page
store. $page.url.pathname
subscribes to that store and returns the current pathname. There are several ways you could apply this.
The following example creates a component Navlink.svelte
, which
page
active
and sets it to true when $page.url.pathname
equals href
. The $:
make it reactive, meaning that Svelte reruns the code whenever either $page.url.pathname
or href
changes.a
element, we pass href
as a prop. Whenever you use the Navlink component, you pass it href
like you would a regular a
element. That is also why we use export let href
.class:active
. This is the Svelte way of applying classes conditionally. Note that this is actually shorthand for class:active={active}
, meaning we apply the class active
when the variable active
(after the equal sign) is true. When the variable and the class share the same name, we can use class:active
. (docs on this subject).active
class however you like.<script>
import { page } from "$app/stores"
export let href
$: active = $page.url.pathname === href
</script>
<a {href} class:active>
<slot />
</a>
<style>
a.active {
color: red;
}
</style>
You can also use a Tailwind class combined with some inline logic:
<a class:text-primary={$page.url.pathname === '/about'} href="/about">About</a>
Or use traditional CSS combined with a ternary operator:
<a href="/about" class="{($page.url.pathname === '/about')? active : inactive}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With