Routing with Svelte

Introduction to Routing in Svelte

In the previous lesson, you learned how to use the tick() function in Svelte to wait for DOM updates before performing actions like scrolling to elements or measuring their dimensions. This lesson builds on your understanding of reactivity and event handling in Svelte by introducing routing, a key concept for building multi-page applications.

Routing allows you to create different pages in your application and navigate between them. For example, you might have a home page, an about page, and a profile page, each with its own content. In Svelte, routing is handled using SvelteKit, a framework that provides a file-based routing system. This means that the structure of your project’s src/routes directory determines the URLs of your application.

In this lesson, you’ll learn how to set up basic routes, create dynamic routes for user profiles, handle query parameters, and navigate between pages. By the end of this lesson, you’ll be able to build a multi-page Svelte application with efficient and reactive routing.

Setting Up Basic Routes

To create a basic route in Svelte, you simply add a +page.svelte file to the src/routes directory. The name of the file determines the URL of the route. For example, a file named src/routes/about/+page.svelte will create a route at /about.

Here’s an example of a basic route for the /about page:

<h1>About Page</h1>
<p>This is the about section of our SvelteKit app.</p>

When you navigate to /about in your browser, you’ll see the content of this file rendered on the page. This is a simple example, but it demonstrates how easy it is to create routes in Svelte.

Dynamic Routes in Svelte

Dynamic routes allow you to create pages that depend on a parameter, such as a user ID or a product ID. In Svelte, dynamic routes are created by adding square brackets ([]) to the folder name in the src/routes directory. For example, a folder named src/routes/profile/[userId] will create a dynamic route where userId is a parameter.

Here’s an example of a dynamic route for user profiles:

<script>
  import { page } from '$app/state';

  let { params } = page;
</script>

<h1>Profile Page</h1>
<p>Viewing profile of user {params.userId}</p>

In this example, the params object contains the route parameters, which you can access using params.userId. When you navigate to /profile/1, the page will display "Viewing profile of user 1." This allows you to create pages that dynamically display content based on the URL.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal