0
0
Svelteframework~30 mins

Component composition in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Component composition
📖 Scenario: You are building a simple Svelte app that shows a list of fruits with their colors. You want to split the UI into smaller parts for better organization.
🎯 Goal: Create two Svelte components: FruitItem.svelte to show one fruit and its color, and FruitList.svelte to show the list of fruits using FruitItem. Compose them so the app displays all fruits with their colors.
📋 What You'll Learn
Create a FruitItem.svelte component that accepts name and color as props and displays them.
Create a FruitList.svelte component that has a list of fruits as an array of objects with name and color.
Use FruitItem inside FruitList to render each fruit.
Ensure the main app file App.svelte renders FruitList.
💡 Why This Matters
🌍 Real World
Component composition is how you build complex user interfaces by combining small, reusable parts. This makes your code easier to manage and update.
💼 Career
Understanding component composition is essential for working with modern frontend frameworks like Svelte, React, or Vue. It is a core skill for frontend developers.
Progress0 / 4 steps
1
Create the FruitItem.svelte component
Create a Svelte component file named FruitItem.svelte. Inside it, declare two props: name and color. Then add markup that shows the fruit name inside a <strong> tag and the color inside a <em> tag.
Svelte
Need a hint?

Use export let to declare props in Svelte.

2
Create the FruitList.svelte component with fruit data
Create a Svelte component file named FruitList.svelte. Inside it, create a variable called fruits that is an array of objects. Each object should have name and color properties with these exact entries: { name: 'Apple', color: 'red' }, { name: 'Banana', color: 'yellow' }, and { name: 'Grape', color: 'purple' }.
Svelte
Need a hint?

Use const fruits = [...] to create the array.

3
Use FruitItem inside FruitList.svelte to render each fruit
In FruitList.svelte, import the FruitItem component. Then use a {#each} block to loop over the fruits array. For each fruit, render <FruitItem /> passing name and color as props from the fruit object.
Svelte
Need a hint?

Use import FruitItem from './FruitItem.svelte' and a {#each} block.

4
Render FruitList inside App.svelte
In the main app file App.svelte, import the FruitList component. Then add <FruitList /> inside the markup to show the fruit list on the page.
Svelte
Need a hint?

Use import FruitList from './FruitList.svelte' and add <FruitList /> in markup.