0
0
Svelteframework~30 mins

Dynamic route parameters in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Dynamic Route Parameters in Svelte
📖 Scenario: You are building a simple blog website using Svelte. Each blog post has a unique ID, and you want to create pages that show the details of each post based on the URL.
🎯 Goal: Build a Svelte app that uses dynamic route parameters to display the correct blog post content based on the URL.
📋 What You'll Learn
Create a data structure with blog posts and their IDs
Set up a dynamic route file to capture the post ID from the URL
Use the route parameter to find and display the correct post
Show a message if the post ID does not exist
💡 Why This Matters
🌍 Real World
Dynamic route parameters are used in websites to show different content based on the URL, like user profiles, product pages, or blog posts.
💼 Career
Understanding dynamic routes is essential for building interactive web apps with frameworks like Svelte, React, or Next.js, which is a common skill in frontend development jobs.
Progress0 / 4 steps
1
Create blog posts data
Create a variable called posts that is an array of objects. Each object should have id and title properties with these exact values: { id: '1', title: 'First Post' }, { id: '2', title: 'Second Post' }, and { id: '3', title: 'Third Post' }.
Svelte
Hint

Use an array with three objects. Each object needs id and title exactly as shown.

2
Create dynamic route file
Create a Svelte file named [id].svelte inside the src/routes folder. Inside this file, import page from $app/stores and create a reactive variable called postId that gets the id parameter from $page.params.id.
Svelte
Hint

Use import { page } from '$app/stores' and a reactive statement $: postId = $page.params.id.

3
Find the post using the route parameter
Inside the [id].svelte file, create a reactive variable called post that finds the object in posts where post.id equals postId.
Svelte
Hint

Use posts.find() to get the post with id matching postId.

4
Display post title or not found message
In the [id].svelte file, add markup inside the <main> tag that shows the post.title if post exists. Otherwise, show the text Post not found.
Svelte
Hint

Use Svelte's {#if} block to show the title or a not found message.