Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you pass props to a layout in sveltekit

Tags:

sveltekit

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!

like image 541
Anders Avatar asked Aug 31 '25 20:08

Anders


1 Answers

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

  1. Imports the default Svelte store page
  2. Creates a reactive boolean 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.
  3. In the 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.
  4. We also add 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)
  5. Style the .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}"
like image 176
Koen Avatar answered Sep 04 '25 07:09

Koen