Implementing Routing in Svelte
Learn how to implement an SPA routing in Svelte using the svelte-routing library.
We'll cover the following...
So far, we've only worked on one page, but most web applications have multiple pages. In this lesson, we're going to take a look at how to implement routing in Svelte to create more pages and navigate between them.
By default, Svelte doesn't have a built-in way to handle routing, so we're going to use a third-party community-developed package called svelte-routing
. We're going to define all routes at the root of our application, App.svelte
:
<script> import { state } from '../state' import Header from '../components/Header.svelte' export let id; const student = $state.students.find(student => [id, Number(id)].includes(student.id)); </script> <Header /> details view for: {id}
We need to import the Router
and Route
components from svelte-routing
. For each route, we want to use the Route
component with a component
prop, where we can pass the component that we want to render. Notice that Route
components can only be used inside the Router
...