0
0
Svelteframework~30 mins

Using data in pages in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Data in Svelte Pages
📖 Scenario: You are building a simple Svelte page to display a list of fruits with their colors. This is like making a small fruit catalog on a webpage.
🎯 Goal: Create a Svelte page that holds a list of fruits and their colors, then show them in a neat list on the page.
📋 What You'll Learn
Create a variable called fruits that holds an array of objects with name and color properties.
Create a variable called highlightColor to store a color string.
Use a {#each} block to loop over fruits and display each fruit's name and color.
Highlight the fruit name with the color stored in highlightColor.
💡 Why This Matters
🌍 Real World
Displaying lists of items with dynamic data is common in websites, like product catalogs or contact lists.
💼 Career
Knowing how to use data and loops in Svelte pages is essential for building interactive web apps and user interfaces.
Progress0 / 4 steps
1
Create the fruits data array
Create a variable called fruits that is an array with these exact objects: { name: 'Apple', color: 'Red' }, { name: 'Banana', color: 'Yellow' }, and { name: 'Grape', color: 'Purple' }.
Svelte
Hint

Use let fruits = [ ... ] and include the objects exactly as shown.

2
Add a highlight color variable
Add a variable called highlightColor and set it to the string 'blue'.
Svelte
Hint

Use let highlightColor = 'blue'; to create the variable.

3
Display the fruits using an each block
Use a {#each} block to loop over fruits and display each fruit's name and color inside a <li> element. Use variables fruit for each item.
Svelte
Hint

Use {#each fruits as fruit} and inside it put a <li> with {fruit.name} and {fruit.color}.

4
Highlight fruit names with the highlight color
Modify the fruit name inside the <li> so that it is wrapped in a <span> with a style attribute that sets color to the highlightColor variable.
Svelte
Hint

Use <span style="color: {highlightColor}">{fruit.name}</span> inside the <li>.