Svelte and SvelteKit course Β· Module 2: Components
Nesting Components
In this lesson3
Just as Yggdrasil has branches, and those have smaller twigs, Svelte components can contain other components.
Example: Viking Village Structure
VikingVillage (root)
βββ TownHall
β βββ ChiefRoom
β βββ MeetingHall
βββ Barracks
β βββ Warrior
β βββ Warrior
β βββ Warrior
βββ Blacksmith
β βββ Forge
βββ Harbor
βββ Ship
βββ ShipImplementation
<!-- VikingVillage.svelte -->
<script>
import TownHall from './TownHall.svelte';
import Barracks from './Barracks.svelte';
import Blacksmith from './Blacksmith.svelte';
import Harbor from './Harbor.svelte';
let villageName = 'Svenheim';
</script>
<div class="village">
<h1>Village: {villageName}</h1>
<TownHall />
<Barracks />
<Blacksmith />
<Harbor />
</div>
<style>
.village {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1rem;
padding: 2rem;
}
</style><!-- Barracks.svelte -->
<script>
import Warrior from './Warrior.svelte';
let warriors = ['Ragnar', 'Bjorn', 'Ivar', 'Ubbe'];
</script>
<div class="barracks">
<h2>Barracks</h2>
{#each warriors as name}
<Warrior {name} />
{/each}
</div><Warrior {name} /> is shorthand for <Warrior name={name} />. The Warrior component receives that value with the $props() rune:
<!-- Warrior.svelte -->
<script>
let { name } = $props();
</script>
<div class="warrior">
<span class="icon">α</span>
<span class="name">{name}</span>
</div>
<style>
.warrior {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem;
background: #3d2914;
border-radius: 4px;
margin: 0.25rem 0;
}
</style>Best Practices for Nesting
- One component = one responsibility
- Do not nest too deeply (max 3-4 levels)
- Extract repeating elements into separate components
- Name components clearly - by what they do, not how they look
Code for this lesson: App.svelte
<script>
// Nesting components - like branches of Yggdrasil
import VikingVillage from './VikingVillage.svelte';
</script>
<VikingVillage name="Kattegat" />
<style>
:global(body) {
margin: 0;
background: #0a0a0a;
}
</style>Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How do you import a component from the src/lib directory through the alias in SvelteKit 3?
Hands-on tasks in the game
- Code editor
Complete the code by importing the Warrior component and using it in the markup