logo
eng-flag

Svelte Cheatsheet

Table of Contents

  1. Components
  2. Reactivity
  3. Props
  4. Logic
  5. Events
  6. Bindings
  7. Lifecycle
  8. Stores
  9. Motion
  10. Transitions
  11. Actions
  12. Classes
  13. Slots
  14. Context API
  15. Special Elements
  16. Module Context
  17. Debugging
  18. Routing (SvelteKit)
  19. Server-Side Rendering
  20. TypeScript Support

Components

Basic Component Structure

<script>
  let name = 'world';
</script>

<main>
  <h1>Hello {name}!</h1>
</main>

<style>
  h1 {
    color: blue;
  }
</style>

Reactivity

Reactive Declarations

<script>
  let count = 0;
  $: doubled = count * 2;

  function handleClick() {
    count += 1;
  }
</script>

<button on:click={handleClick}>
  Clicked {count} {count === 1 ? 'time' : 'times'}
</button>

<p>{count} doubled is {doubled}</p>

Reactive Statements

<script>
  let count = 0;

  $: {
    console.log(`The count is ${count}`);
  }

  $: if (count >= 10) {
    alert('Count is dangerously high!');
    count = 9;
  }
</script>

Props

Declaring Props

<script>
  export let name;
  export let age = 30; // default value
</script>

<p>{name} is {age} years old.</p>

Spread Props

<script>
  import Info from './Info.svelte';
  
  const pkg = {
    name: 'svelte',
    version: 3,
    speed: 'blazing',
    website: 'https://svelte.dev'
  };
</script>

<Info {...pkg} />

Logic

If Blocks

{#if user.loggedIn}
  <button on:click={logout}>Log out</button>
{:else}
  <button on:click={login}>Log in</button>
{/if}

Each Blocks

<ul>
  {#each items as item, index (item.id)}
    <li>{index + 1}: {item.name}</li>
  {/each}
</ul>

Await Blocks

{#await promise}
  <p>...waiting</p>
{:then number}
  <p>The number is {number}</p>
{:catch error}
  <p style="color: red">{error.message}</p>
{/await}

Events

Event Handling

<script>
  function handleClick() {
    alert('Button clicked!');
  }
</script>

<button on:click={handleClick}>Click me</button>

Event Modifiers

<button on:click|once|preventDefault={handleClick}>Click me</button>

Component Events

<script>
  import { createEventDispatcher } from 'svelte';

  const dispatch = createEventDispatcher();

  function sayHello() {
    dispatch('message', {
      text: 'Hello!'
    });
  }
</script>

<button on:click={sayHello}>Say hello</button>

Bindings

Two-way Binding

<script>
  let name = 'world';
</script>

<input bind:value={name}>

<h1>Hello {name}!</h1>

Checkbox Binding

<script>
  let checked = false;
</script>

<label>
  <input type="checkbox" bind:checked>
  Is checked: {checked}
</label>

Lifecycle

onMount

<script>
  import { onMount } from 'svelte';

  let data = [];

  onMount(async () => {
    const res = await fetch('https://api.example.com/data');
    data = await res.json();
  });
</script>

onDestroy

<script>
  import { onDestroy } from 'svelte';

  let interval = setInterval(() => {
    console.log('Tick');
  }, 1000);

  onDestroy(() => {
    clearInterval(interval);
  });
</script>

Stores

Writable Store

import { writable } from 'svelte/store';

export const count = writable(0);

Using Stores

<script>
  import { count } from './stores.js';

  function increment() {
    count.update(n => n + 1);
  }
</script>

<h1>The count is {$count}</h1>
<button on:click={increment}>+</button>

Motion

Tweened

<script>
  import { tweened } from 'svelte/motion';
  import { cubicOut } from 'svelte/easing';

  const progress = tweened(0, {
    duration: 400,
    easing: cubicOut
  });
</script>

<progress value={$progress}></progress>

<button on:click={() => progress.set(0)}>
  0%
</button>

<button on:click={() => progress.set(1)}>
  100%
</button>

Transitions

Fade Transition

<script>
  import { fade } from 'svelte/transition';
  let visible = true;
</script>

<label>
  <input type="checkbox" bind:checked={visible}>
  visible
</label>

{#if visible}
  <p transition:fade>Fades in and out</p>
{/if}

Actions

Use Directive

<script>
  function pannable(node) {
    let x;
    let y;

    function handleMousedown(event) {
      x = event.clientX;
      y = event.clientY;

      node.dispatchEvent(new CustomEvent('panstart', {
        detail: { x, y }
      }));

      window.addEventListener('mousemove', handleMousemove);
      window.addEventListener('mouseup', handleMouseup);
    }

    function handleMousemove(event) {
      const dx = event.clientX - x;
      const dy = event.clientY - y;
      x = event.clientX;
      y = event.clientY;

      node.dispatchEvent(new CustomEvent('panmove', {
        detail: { x, y, dx, dy }
      }));
    }

    function handleMouseup(event) {
      x = event.clientX;
      y = event.clientY;

      node.dispatchEvent(new CustomEvent('panend', {
        detail: { x, y }
      }));

      window.removeEventListener('mousemove', handleMousemove);
      window.removeEventListener('mouseup', handleMouseup);
    }

    node.addEventListener('mousedown', handleMousedown);

    return {
      destroy() {
        node.removeEventListener('mousedown', handleMousedown);
      }
    };
  }
</script>

<div use:pannable
  on:panstart={handlePanStart}
  on:panmove={handlePanMove}
  on:panend={handlePanEnd}>
  Drag me!
</div>

Classes

Class Directive

<script>
  let active = true;
  let danger = false;
</script>

<div class:active class:danger>
  Class example
</div>

Slots

Default Slot

<!-- Card.svelte -->
<div class="card">
  <slot></slot>
</div>

<!-- App.svelte -->
<Card>
  <h2>Card Title</h2>
  <p>Card content</p>
</Card>

Named Slots

<!-- Layout.svelte -->
<div class="layout">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

<!-- App.svelte -->
<Layout>
  <h1 slot="header">Page Title</h1>
  <p>Main content</p>
  <p slot="footer">Copyright 2023</p>
</Layout>

Context API

Setting Context

<script>
  import { setContext } from 'svelte';

  setContext('theme', {
    primaryColor: 'blue',
    textColor: 'white'
  });
</script>

Getting Context

<script>
  import { getContext } from 'svelte';

  const { primaryColor, textColor } = getContext('theme');
</script>

Special Elements

svelte:head

<svelte:head>
  <title>My Svelte App</title>
  <meta name="description" content="This is my Svelte app">
</svelte:head>

svelte:window

<script>
  let y;

  function handleScroll(event) {
    y = window.scrollY;
  }
</script>

<svelte:window on:scroll={handleScroll}/>

<p>Scrolled to {y}</p>

Module Context

Module Script

<script context="module">
  let count = 0;

  export function incrementCount() {
    count += 1;
  }
</script>

<script>
  import { incrementCount } from './Counter.svelte';
</script>

<button on:click={incrementCount}>
  Clicks: {count}
</button>

Debugging

@debug

<script>
  let user = { name: 'John', age: 30 };
</script>

{@debug user}

<h1>{user.name}</h1>

Routing (SvelteKit)

Basic Routing

// src/routes/+page.svelte
<h1>Home</h1>

// src/routes/about/+page.svelte
<h1>About</h1>

// src/routes/[slug]/+page.svelte
<script>
  export let data;
</script>

<h1>{data.title}</h1>
<div>{@html data.content}</div>

Server-Side Rendering

Load Function

// src/routes/blog/[slug]/+page.server.js
export async function load({ params }) {
  const post = await getPostFromDatabase(params.slug);
  return { post };
}

TypeScript Support

TypeScript in Svelte

<script lang="ts">
  let count: number = 0;
  
  function increment(): void {
    count += 1;
  }
</script>

<button on:click={increment}>
  Clicks: {count}
</button>

2024 © All rights reserved - buraxta.com