Page 4: Components, Props, and Stores

4. Components, Props, and Stores

SvelteKit is built upon the Svelte component model. Components are reusable building blocks of your UI.

4.1. Svelte Components and Props

A .svelte file defines a component, encapsulating HTML, CSS, and JavaScript in a single file. You declare props using export let.

<!-- src/lib/Button.svelte -->
<script>
  export let text = 'Click Me';
  export let onClick = () => {};
</script>
<button on:click={onClick}>{text}</button>

<style>
  button {
    padding: 10px 20px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
  }
</style>

Use it in a parent component by passing props:

<!-- src/routes/+page.svelte -->
<script>
  import Button from '$lib/Button.svelte';
  function handleClick() {
    alert('Button clicked!');
  }
</script>
<Button text="Learn More" onClick={handleClick} />

4.2. State Management with Svelte Stores

Stores are objects used to share state between multiple components and update it reactively.

// src/lib/stores.js
import { writable } from 'svelte/store';
export const count = writable(0);

Using a store in a component:

<!-- src/routes/+page.svelte -->
<script>
  import { count } from '$lib/stores';
</script>
<h1>Count: {$count}</h1>
<button on:click={() => count.update(n => n + 1)}>Increment</button>
<button on:click={() => count.set(0)}>Reset</button>

The $count syntax subscribes to the store's value and updates automatically.