Chapter 4: Building Components
In this chapter, we'll dive deeper into advanced component patterns in Svelte. You'll learn about component lifecycle, slots for composition, and how to create truly reusable components.
Component Lifecycle
Svelte components have lifecycle functions that let you run code at particular times in the component's life:
- onMount: Runs after the component is mounted to the DOM. Perfect for initializing data.
- beforeUpdate: Runs before the DOM is updated.
- afterUpdate: Runs after the DOM is updated.
- onDestroy: Runs when the component is destroyed.
<script>
import { onMount } from 'svelte';
onMount(() => {
console.log('Component mounted!');
// Initialize data here
});
</script>
Using Slots
Slots allow components to accept content from parent components, enabling flexible composition:
<!-- Card.svelte -->
<div class="card">
<slot></slot>
</div>
<style>
.card {
border: 1px solid #ccc;
padding: 1rem;
}
</style>
Usage:
<Card>
<h2>Hello!</h2>
<p>This content goes into the slot.</p>
</Card>
Named Slots
For more complex layouts, use named slots:
<!-- Layout.svelte -->
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
Usage:
<Layout>
<div slot="header">Header content</div>
<p>Main content</p>
<div slot="footer">Footer content</div>
</Layout>
Event Forwarding
Forward events from child components to parent components:
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function handleClick() {
dispatch('click', { message: 'Button clicked!' });
}
</script>
<button on:click={handleClick}>Click me</button>
You now have the tools to build flexible, reusable Svelte components!