Lesson 5
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:

svelte
1<h1>About Page</h1> 2<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:

svelte
1<script> 2 import { page } from '$app/state'; 3 4 let { params } = page; 5</script> 6 7<h1>Profile Page</h1> 8<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.

Working with Query Parameters

Query parameters are used to pass additional information in the URL, such as search terms or filters. In Svelte, you can access query parameters using the url object from $app/state.

Here’s an example of a search page that uses query parameters:

svelte
1<script> 2 import { page } from '$app/state'; 3 4 let { url } = page; 5</script> 6 7<h1>Search Page</h1> 8<p>Searching for: {url.searchParams.get('term') ?? "Nothing"}</p>

In this example, the url.searchParams.get('term') method retrieves the value of the term query parameter. If the parameter is not present, it defaults to "Nothing." When you navigate to /search?term=svelte, the page will display "Searching for: svelte."

Navigating Between Routes & Reactive Routing with Svelte

Svelte’s reactivity system makes it easy to create dynamic and interactive routing experiences. You can use the <a> tag for simple navigation or make use of reactive variables to dynamically update URLs based on user input or other changes in your application.

Here’s an example of a navigation bar with links to different pages:

svelte
1<script> 2 let userId = $state(1); 3 let searchText = $state(""); 4</script> 5 6<h1>Welcome to My App</h1> 7 8<nav> 9 <a href="/">Home</a> 10 <a href="/about">About</a> 11 <a href={`/profile/${userId}`}>Profile of {userId}</a> 12</nav> 13 14<div> 15 <input type="text" bind:value={searchText} /> 16 <a href="/search?term={searchText}">Search data</a> 17</div> 18<button onclick={() => userId++}>Next user</button> 19<button onclick={() => userId--}>Previous user</button>
How It Works:
  • Navigating Between Routes:
    The <a> tags create links to the home page, about page, and user profiles. The href attribute for the profile link dynamically updates based on the userId variable.

  • Reactive Routing:
    The $state rune makes the userId and searchText variables reactive. When userId changes, the profile link automatically updates to reflect the new ID. When searchText changes, the search link updates to include the search term as a query parameter. This reactivity is achieved through the bind:value directive, which synchronizes the input field with the searchText variable in real-time.

  • Dynamic Interaction:
    Buttons allow incrementing and decrementing the userId to demonstrate how the routing updates dynamically. As you type in the search input, the search link updates instantly to include the current search term, enhancing the interactivity of your application.

This approach combines standard navigation techniques with Svelte’s powerful reactivity, providing a seamless user experience where links update dynamically based on your application state.

Summary and Next Steps

In this lesson, you’ve learned how to implement routing in Svelte using SvelteKit. You explored basic routes, dynamic routes, and query parameters, and learned how to navigate between pages using links and programmatic navigation. You also saw how to make routing reactive using Svelte’s $state rune, allowing you to create dynamic and interactive routing experiences.

In the upcoming practice exercises, you’ll have the opportunity to apply these concepts by building a multi-page Svelte application. You’ll experiment with creating routes, handling dynamic parameters, and using query parameters to filter data. Remember that the CodeSignal environment has Svelte 5 pre-installed, so you can focus on coding without worrying about setup.

Great job completing this lesson! You’re now ready to take on the challenges of building scalable and interactive Svelte applications. Keep up the good work!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.