Learn how to break down your SvelteKit pages into smaller “components” in this tutorial.
Components are core to SvelteKit, so let’s spend this lesson learning how they work by adding a navigation bar to our layout.
First we need a home for all of our components. Create a directory called
src so you end up with
/src/lib/. Inside your new
lib directory create
Nav.svelte with the following:
Let’s add this to our layout at
/src/routes/__layout.svelte. First we’ll import the module at the top of file:
In Svelte, a capitalized tag like
<Widget> indicates a component. So we can call our Nav component like this:
If we put that all together, our layout will look something like this:
Take a look at your new navigation bar in the browser!
Let’s take this a step further by adding some props to the component to allow for further customization.
You may have noticed the unused
.alt style we specified in
<style> as part of the
Nav component. Let’s say we want the
Nav to apply the
alt class when it’s called from this layout while allowing us to still call the original version of the component from elsewhere on the site. We can do this by setting props.
We’ll start by declaring the prop in our component:
This initializes the className prop to an empty string which will be overridden if we pass a parameter to this component. Now we can use this to set the class on our
So now the whole file looks like this:
Now you should have a blue nav bar when you view your site. Pretty neat!
In the next lesson we’ll go over the basics of templating in SvelteKit.