Svelte and SvelteKit course Β· Module 2: Components

Nesting Components

2 min read Β·
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
    └── Ship

Implementation

<!-- 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

  1. One component = one responsibility
  2. Do not nest too deeply (max 3-4 levels)
  3. Extract repeating elements into separate components
  4. 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. 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

Useful articles