'Can you pass props to a layout in 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!
Solution 1:[1]
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
- Imports the default Svelte store
page - Creates a reactive boolean
activeand sets it to true when$page.url.pathnameequalshref. The$:make it reactive, meaning that Svelte reruns the code whenever either$page.url.pathnameorhrefchanges. - In the
aelement, we passhrefas a prop. Whenever you use the Navlink component, you pass ithreflike you would a regularaelement. That is also why we useexport let href. - We also add
class:active. This is the Svelte way of applying classes conditionally. Note that this is actually shorthand forclass:active={active}, meaning we apply the classactivewhen the variableactive(after the equal sign) is true. When the variable and the class share the same name, we can useclass:active. (docs on this subject) - Style the
.activeclass 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}"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Koen |
