--- title: Svelte date: 2025-08-16 10:30:00 background: bg-[#FF3E00] tags: - svelte - web categories: - Programming intro: | A Svelte cheat sheet with the most important concepts, functions, reactivity, and more. A complete quick reference for beginners, updated for Svelte 5. plugins: - copyCode - runCode --- ## Getting Started ### Basic Syntax ```js

Hello {name}!

``` ### Expressions ```js

Hello {fullName()}!

``` ### Attributes ```js Avatar ``` ### Functions in Markup ```js

Hi {name()}!

``` ### Conditional Rendering {.col-span-2} ```js {#if temperature >= 20}

It is {temperature}°C (Warm) in {city}

{:else}

It is {temperature}°C in {city}

{/if} ``` Note: Svelte components must always return a root element or content. ## Components ### Functional Component ```js
Hello
{name}
``` ### Embed an internal Component ```js
``` ### Embed an external Component ```js
``` Note: External components should be installed via npm first. ### Advanced Functional Components ```js

{fullName()}

``` ## Properties {.cols-2} ### Passing Properties to a Component ```js ``` ### Assigning the Properties from a Component ```js

{firstName} {lastName} is {age}.

``` ## State {.cols-1} ### Local State ```js

{name}

``` ## Events {.cols-1} ### Event Listener ```js Say Hi ``` Note: The most common event listeners are `onclick` and `onsubmit`. ## Loops {.cols-2} ### Looping through an Array ```js ``` ### Looping through an Array of Objects ```js ``` ## Forms {.cols-1} ### Form Example ```js
``` ## CSS {.cols-1} ### Scoped CSS ```js
Zehan Khan
``` ## Fetching Data {.cols-1} ### Fetching Data with onMount ```js {#if loading}

Loading notifications...

{:else} {/if} ``` Note: Use `onMount` for side effects like API calls. ## Lifecycle Hooks {.cols-1} ### onMount ```js ``` ### beforeUpdate ```js ``` ### afterUpdate ```js ``` ### onDestroy ```js ``` Note: Svelte lifecycle functions are similar to React Hooks, but they are imported individually and used directly in the `

Count: {$count}

Double: {$double}

``` ### Readable Store ```js import { readable } from 'svelte/store'; export const time = readable(new Date(), function start(set) { const interval = setInterval(() => { set(new Date()); }, 1000); return function stop() { clearInterval(interval); }; }); ``` ### Reactive Declarations ```js

{sum}

``` ### Reactive Statements with Side Effects ```js ``` ### Bind to DOM Properties ```js