## docs/svelte/index.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Svelte --- ## docs/svelte/01-introduction/index.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Introduction --- ## docs/svelte/01-introduction/01-overview.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Overview --- Svelte is a framework for building user interfaces on the web. It uses a compiler to turn declarative components written in HTML, CSS and JavaScript... ```svelte ``` ...into lean, tightly optimized JavaScript. You can use it to build anything on the web, from standalone components to ambitious full stack apps (using Svelte's companion application framework, [SvelteKit](../kit)) and everything in between. These pages serve as reference documentation. If you're new to Svelte, we recommend starting with the [interactive tutorial](/tutorial) and coming back here when you have questions. You can also try Svelte online in the [playground](/playground) or, if you need a more fully-featured environment, on [StackBlitz](https://sveltekit.new). ## docs/svelte/01-introduction/02-getting-started.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Getting started --- We recommend using [SvelteKit](../kit), the official application framework from the Svelte team powered by [Vite](https://vite.dev/): ```bash npx sv create myapp cd myapp npm install npm run dev ``` Don't worry if you don't know Svelte yet! You can ignore all the nice features SvelteKit brings on top for now and dive into it later. ## Alternatives to SvelteKit You can also use Svelte directly with Vite by running `npm create vite@latest` and selecting the `svelte` option. With this, `npm run build` will generate HTML, JS and CSS files inside the `dist` directory using [vite-plugin-svelte](https://github.com/sveltejs/vite-plugin-svelte). In most cases, you will probably need to [choose a routing library](faq#Is-there-a-router) as well. There are also plugins for [Rollup](https://github.com/sveltejs/rollup-plugin-svelte), [Webpack](https://github.com/sveltejs/svelte-loader) [and a few others](https://sveltesociety.dev/packages?category=build-plugins), but we recommend Vite. ## Editor tooling The Svelte team maintains a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode), and there are integrations with various other [editors](https://sveltesociety.dev/resources#editor-support) and tools as well. You can also check your code from the command line using [sv check](https://github.com/sveltejs/cli). ## Getting help Don't be shy about asking for help in the [Discord chatroom](/chat)! You can also find answers on [Stack Overflow](https://stackoverflow.com/questions/tagged/svelte). ## docs/svelte/01-introduction/03-svelte-files.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: .svelte files --- Components are the building blocks of Svelte applications. They are written into `.svelte` files, using a superset of HTML. All three sections — script, styles and markup — are optional. ```svelte /// file: MyComponent.svelte ``` ## ` ``` You can `export` bindings from this block, and they will become exports of the compiled module. You cannot `export default`, since the default export is the component itself. > In Svelte 4, this script tag was created using ` ``` You can specify a fallback value for a prop. It will be used if the component's consumer doesn't specify the prop on the component when instantiating the component, or if the passed value is `undefined` at some point. ```svelte ``` To get all properties, use rest syntax: ```svelte ``` You can use reserved words as prop names. ```svelte ``` If you're using TypeScript, you can declare the prop types: ```svelte ``` If you're using JavaScript, you can declare the prop types using JSDoc: ```svelte ``` If you export a `const`, `class` or `function`, it is readonly from outside the component. ```svelte ``` Readonly props can be accessed as properties on the element, tied to the component using [`bind:this` syntax](bindings#bind:this). ### Reactive variables To change component state and trigger a re-render, just assign to a locally declared variable that was declared using the `$state` rune. Update expressions (`count += 1`) and property assignments (`obj.x = y`) have the same effect. ```svelte ``` Svelte's ` ``` If you'd like to react to changes to a prop, use the `$derived` or `$effect` runes instead. ```svelte ``` For more information on reactivity, read the documentation around runes. ## docs/svelte/01-introduction/xx-reactivity-fundamentals.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Reactivity fundamentals --- Reactivity is at the heart of interactive UIs. When you click a button, you expect some kind of response. It's your job as a developer to make this happen. It's Svelte's job to make your job as intuitive as possible, by providing a good API to express reactive systems. ## Runes Svelte 5 uses _runes_, a powerful set of primitives for controlling reactivity inside your Svelte components and inside `.svelte.js` and `.svelte.ts` modules. Runes are function-like symbols that provide instructions to the Svelte compiler. You don't need to import them from anywhere — when you use Svelte, they're part of the language. The following sections introduce the most important runes for declare state, derived state and side effects at a high level. For more details refer to the later sections on [state](state) and [side effects](side-effects). ## `$state` Reactive state is declared with the `$state` rune: ```svelte ``` You can also use `$state` in class fields (whether public or private): ```js // @errors: 7006 2554 class Todo { done = $state(false); text = $state(); constructor(text) { this.text = text; } } ``` > In Svelte 4, state was implicitly reactive if the variable was declared at the top level > > ```svelte > > > > ``` ## `$derived` Derived state is declared with the `$derived` rune: ```svelte

{count} doubled is {doubled}

``` The expression inside `$derived(...)` should be free of side-effects. Svelte will disallow state changes (e.g. `count++`) inside derived expressions. As with `$state`, you can mark class fields as `$derived`. > In Svelte 4, you could use reactive statements for this. > > ```svelte > > > > >

{count} doubled is {doubled}

> ``` > > This only worked at the top level of a component. ## `$effect` To run _side-effects_ when the component is mounted to the DOM, and when values change, we can use the `$effect` rune ([demo](/REMOVED)): ```svelte ``` The function passed to `$effect` will run when the component mounts, and will re-run after any changes to the values it reads that were declared with `$state` or `$derived` (including those passed in with `$props`). Re-runs are batched (i.e. changing `color` and `size` in the same moment won't cause two separate runs), and happen after any DOM updates have been applied. > In Svelte 4, you could use reactive statements for this. > > ```svelte > > > > ``` > > This only worked at the top level of a component. ## docs/svelte/02-runes/index.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Runes --- ## docs/svelte/02-runes/01-what-are-runes.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: What are runes? --- > > A letter or mark used as a mystical or magic symbol. Runes are symbols that you use in `.svelte` and `.svelte.js`/`.svelte.ts` files to control the Svelte compiler. If you think of Svelte as a language, runes are part of the syntax — they are _keywords_. Runes have a `$` prefix and look like functions: ```js let message = $state('hello'); ``` They differ from normal JavaScript functions in important ways, however: - You don't need to import them — they are part of the language - They're not values — you can't assign them to a variable or pass them as arguments to a function - Just like JavaScript keywords, they are only valid in certain positions (the compiler will help you if you put them in the wrong place) > Runes didn't exist prior to Svelte 5. ## docs/svelte/02-runes/02-$state.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $state --- The `$state` rune allows you to create _reactive state_, which means that your UI _reacts_ when it changes. ```svelte ``` Unlike other frameworks you may have encountered, there is no API for interacting with state — `count` is just a number, rather than an object or a function, and you can update it like you would update any other variable. ### Deep state If `$state` is used with an array or a simple object, the result is a deeply reactive _state proxy_. [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) allow Svelte to run code when you read or write properties, including via methods like `array.push(...)`, triggering granular updates. State is proxified recursively until Svelte finds something other than an array or simple object. In a case like this... ```js let todos = $state([ { done: false, text: 'add more todos' } ]); ``` ...modifying an individual todo's property will trigger updates to anything in your UI that depends on that specific property: ```js let todos = [{ done: false, text: 'add more todos' }]; //cut todos[0].done = !todos[0].done; ``` If you push a new object to the array, it will also be proxified: ```js // @filename: ambient.d.ts declare global { const todos: Array<{ done: boolean, text: string }> } // @filename: index.js //cut todos.push({ done: false, text: 'eat lunch' }); ``` Note that if you destructure a reactive value, the references are not reactive — as in normal JavaScript, they are evaluated at the point of destructuring: ```js let todos = [{ done: false, text: 'add more todos' }]; //cut let { done, text } = todos[0]; // this will not affect the value of `done` todos[0].done = !todos[0].done; ``` ### Classes You can also use `$state` in class fields (whether public or private): ```js // @errors: 7006 2554 class Todo { done = $state(false); text = $state(); constructor(text) { this.text = text; } reset() { this.text = ''; this.done = false; } } ``` When calling methods in JavaScript, the value of [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) matters. This won't work, because `this` inside the `reset` method will be the ` ``` You can either use an inline function... ```svelte ``` ...or use an arrow function in the class definition: ```js // @errors: 7006 2554 class Todo { done = $state(false); text = $state(); constructor(text) { this.text = text; } reset = () => { this.text = ''; this.done = false; } } ``` ## `$state.raw` In cases where you don't want objects and arrays to be deeply reactive you can use `$state.raw`. State declared with `$state.raw` cannot be mutated; it can only be _reassigned_. In other words, rather than assigning to a property of an object, or using an array method like `push`, replace the object or array altogether if you'd like to update it: ```js let person = $state.raw({ name: 'Heraclitus', age: 49 }); // this will have no effect person.age += 1; // this will work, because we're creating a new person person = { name: 'Heraclitus', age: 50 }; ``` This can improve performance with large arrays and objects that you weren't planning to mutate anyway, since it avoids the cost of making them reactive. Note that raw state can _contain_ reactive state (for example, a raw array of reactive objects). ## `$state.snapshot` To take a static snapshot of a deeply reactive `$state` proxy, use `$state.snapshot`: ```svelte ``` This is handy when you want to pass some state to an external library or API that doesn't expect a proxy, such as `structuredClone`. ## Passing state into functions JavaScript is a _pass-by-value_ language — when you call a function, the arguments are the _values_ rather than the _variables_. In other words: ```js /// file: index.js // @filename: index.js //cut /** * @param {number} a * @param {number} b */ function add(a, b) { return a + b; } let a = 1; let b = 2; let total = add(a, b); console.log(total); // 3 a = 3; b = 4; console.log(total); // still 3! ``` If `add` wanted to have access to the _current_ values of `a` and `b`, and to return the current `total` value, you would need to use functions instead: ```js /// file: index.js // @filename: index.js //cut /** * @param {() => number} getA * @param {() => number} getB */ function add(getA, getB) { return() => getA() + getB(); } let a = 1; let b = 2; let total = add(() => a, () => b); console.log(total()); // 3 a = 3; b = 4; console.log(total()); // 7 ``` State in Svelte is no different — when you reference something declared with the `$state` rune... ```js let a =$state(1); let b =$state(2); ``` ...you're accessing its _current value_. Note that 'functions' is broad — it encompasses properties of proxies and [`get`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)/[`set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) properties... ```js /// file: index.js // @filename: index.js //cut /** * @param {{ a: number, b: number }} input */ function add(input) { return { get value() { return input.a + input.b; } }; } let input = $state({ a: 1, b: 2 }); let total = add(input); console.log(total.value); // 3 input.a = 3; input.b = 4; console.log(total.value); // 7 ``` ...though if you find yourself writing code like that, consider using [classes](#Classes) instead. ## docs/svelte/02-runes/03-$derived.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $derived --- Derived state is declared with the `$derived` rune: ```svelte

{count} doubled is {doubled}

``` The expression inside `$derived(...)` should be free of side-effects. Svelte will disallow state changes (e.g. `count++`) inside derived expressions. As with `$state`, you can mark class fields as `$derived`. ## `$derived.by` Sometimes you need to create complex derivations that don't fit inside a short expression. In these cases, you can use `$derived.by` which accepts a function as its argument. ```svelte ``` In essence, `$derived(expression)` is equivalent to `$derived.by(() => expression)`. ## Understanding dependencies Anything read synchronously inside the `$derived` expression (or `$derived.by` function body) is considered a _dependency_ of the derived state. When the state changes, the derived will be marked as _dirty_ and recalculated when it is next read. To exempt a piece of state from being treated as a dependency, use [`untrack`](svelte#untrack). ## docs/svelte/02-runes/04-$effect.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $effect --- Effects are what make your application _do things_. When Svelte runs an effect function, it tracks which pieces of state (and derived state) are accessed (unless accessed inside [`untrack`](svelte#untrack)), and re-runs the function when that state later changes. Most of the effects in a Svelte app are created by Svelte itself — they're the bits that update the text in `

hello {name}!

` when `name` changes, for example. But you can also create your own effects with the `$effect` rune, which is useful when you need to synchronize an external system (whether that's a library, or a `` element, or something across a network) with state inside your Svelte app. Your effects run after the component has been mounted to the DOM, and in a [microtask](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) after state changes ([demo](/REMOVED)): ```svelte ``` Re-runs are batched (i.e. changing `color` and `size` in the same moment won't cause two separate runs), and happen after any DOM updates have been applied. You can place `$effect` anywhere, not just at the top level of a component, as long as it is called during component initialization (or while a parent effect is active). It is then tied to the lifecycle of the component (or parent effect) and will therefore destroy itself when the component unmounts (or the parent effect is destroyed). You can return a function from `$effect`, which will run immediately before the effect re-runs, and before it is destroyed ([demo](/REMOVED)). ```svelte

{count}

``` ### Understanding dependencies `$effect` automatically picks up any reactive values (`$state`, `$derived`, `$props`) that are _synchronously_ read inside its function body and registers them as dependencies. When those dependencies change, the `$effect` schedules a rerun. Values that are read _asynchronously_ — after an `await` or inside a `setTimeout`, for example — will not be tracked. Here, the canvas will be repainted when `color` changes, but not when `size` changes ([demo](/REMOVED)): ```ts // @filename: index.ts declare let canvas: { width: number; height: number; getContext(type: '2d', options?: CanvasRenderingContext2DSettings): CanvasRenderingContext2D; }; declare let color: string; declare let size: number; //cut $effect(() => { const context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); // this will re-run whenever `color` changes... context.fillStyle = color; setTimeout(() => { // ...but not when `size` changes context.fillRect(0, 0, size, size); }, 0); }); ``` An effect only reruns when the object it reads changes, not when a property inside it changes. (If you want to observe changes _inside_ an object at dev time, you can use [`$inspect`]($inspect).) ```svelte

{state.value} doubled is {derived.value}

``` An effect only depends on the values that it read the last time it ran. If `a` is true, changes to `b` will [not cause this effect to rerun](/REMOVED): ```ts let a = false; let b = false; //cut $effect(() => { console.log('running'); if (a || b) { console.log('inside if block'); } }); ``` ## `$effect.pre` In rare cases, you may need to run code _before_ the DOM updates. For this we can use the `$effect.pre` rune: ```svelte
{#each messages as message}

{message}

{/each}
``` Apart from the timing, `$effect.pre` works exactly like `$effect`. ## `$effect.tracking` The `$effect.tracking` rune is an advanced feature that tells you whether or not the code is running inside a tracking context, such as an effect or inside your template ([demo](/REMOVED)): ```svelte

in template: {$effect.tracking()}

``` This allows you to (for example) add things like subscriptions without causing memory leaks, by putting them in child effects. Here's a `readable` function that listens to changes from a callback function as long as it's inside a tracking context: ```ts import { tick } from 'svelte'; export default function readable( initial_value: T, start: (callback: (update: (v: T) => T) => T) => () => void ) { let value = $state(initial_value); let subscribers = 0; let stop: null | (() => void) = null; return { get value() { // If in a tracking context ... if ($effect.tracking()) { $effect(() => { // ...and there's no subscribers yet... if (subscribers === 0) { // ...invoke the function and listen to changes to update state stop = start((fn) => (value = fn(value))); } subscribers++; // The return callback is called once a listener unlistens return () => { tick().then(() => { subscribers--; // If it was the last subscriber... if (subscribers === 0) { // ...stop listening to changes stop?.(); stop = null; } }); }; }); } return value; } }; } ``` ## `$effect.root` The `$effect.root` rune is an advanced feature that creates a non-tracked scope that doesn't auto-cleanup. This is useful for nested effects that you want to manually control. This rune also allows for the creation of effects outside of the component initialisation phase. ```svelte ``` ## When not to use `$effect` In general, `$effect` is best considered something of an escape hatch — useful for things like analytics and direct DOM manipulation — rather than a tool you should use frequently. In particular, avoid using it to synchronise state. Instead of this... ```svelte ``` ...do this: ```svelte ``` You might be tempted to do something convoluted with effects to link one value to another. The following example shows two inputs for "money spent" and "money left" that are connected to each other. If you update one, the other should update accordingly. Don't use effects for this ([demo](/REMOVED)): ```svelte ``` Instead, use callbacks where possible ([demo](/REMOVED)): ```svelte ``` If you need to use bindings, for whatever reason (for example when you want some kind of "writable `$derived`"), consider using getters and setters to synchronise state ([demo](/REMOVED)): ```svelte ``` If you absolutely have to update `$state` within an effect and run into an infinite loop because you read and write to the same `$state`, use [untrack](svelte#untrack). ## docs/svelte/02-runes/05-$props.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $props --- The inputs to a component are referred to as _props_, which is short for _properties_. You pass props to components just like you pass attributes to elements: ```svelte ``` On the other side, inside `MyComponent.svelte`, we can receive props with the `$props` rune... ```svelte

this component is {props.adjective}

``` ...though more commonly, you'll [_destructure_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) your props: ```svelte

this component is {adjective}

``` ## Fallback values Destructuring allows us to declare fallback values, which are used if the parent component does not set a given prop: ```js let { adjective = 'happy' } = $props(); ``` ## Renaming props We can also use the destructuring assignment to rename props, which is necessary if they're invalid identifiers, or a JavaScript keyword like `super`: ```js let { super: trouper = 'lights are gonna find me' } = $props(); ``` ## Rest props Finally, we can use a _rest property_ to get, well, the rest of the props: ```js let { a, b, c, ...others } = $props(); ``` ## Updating props References to a prop inside a component update when the prop itself updates — when `count` changes in `App.svelte`, it will also change inside `Child.svelte`. But the child component is able to temporarily override the prop value, which can be useful for unsaved ephemeral state ([demo](/REMOVED)): ```svelte ``` ```svelte ``` While you can temporarily _reassign_ props, you should not _mutate_ props unless they are [bindable]($bindable). If the prop is a regular object, the mutation will have no effect ([demo](/REMOVED)): ```svelte ``` ```svelte ``` If the prop is a reactive state proxy, however, then mutations _will_ have an effect but you will see an [`ownership_invalid_mutation`](runtime-warnings#Client-warnings-ownership_invalid_mutation) warning, because the component is mutating state that does not 'belong' to it ([demo](/REMOVED)): ```svelte ``` ```svelte ``` The fallback value of a prop not declared with `$bindable` is left untouched — it is not turned into a reactive state proxy — meaning mutations will not cause updates ([demo](/REMOVED)) ```svelte ``` In summary: don't mutate props. Either use callback props to communicate changes, or — if parent and child should share the same object — use the [`$bindable`]($bindable) rune. ## Type safety You can add type safety to your components by annotating your props, as you would with any other variable declaration. In TypeScript that might look like this... ```svelte ``` ...while in JSDoc you can do this: ```svelte ``` You can, of course, separate the type declaration from the annotation: ```svelte ``` Adding types is recommended, as it ensures that people using your component can easily discover which props they should provide. ## docs/svelte/02-runes/06-$bindable.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $bindable --- Ordinarily, props go one way, from parent to child. This makes it easy to understand how data flows around your app. In Svelte, component props can be _bound_, which means that data can also flow _up_ from child to parent. This isn't something you should do often, but it can simplify your code if used sparingly and carefully. It also means that a state proxy can be _mutated_ in the child. To mark a prop as bindable, we use the `$bindable` rune: ```svelte /// file: FancyInput.svelte ``` Now, a component that uses `` can add the [`bind:`](bind) directive ([demo](/REMOVED)): ```svelte /// App.svelte

{message}

``` The parent component doesn't _have_ to use `bind:` — it can just pass a normal prop. Some parents don't want to listen to what their children have to say. In this case, you can specify a fallback value for when no prop is passed at all: ```js /// file: FancyInput.svelte let { value = $bindable('fallback'), ...props } = $props(); ``` ## docs/svelte/02-runes/07-$inspect.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $inspect --- The `$inspect` rune is roughly equivalent to `console.log`, with the exception that it will re-run whenever its argument changes. `$inspect` tracks reactive state deeply, meaning that updating something inside an object or array using fine-grained reactivity will cause it to re-fire ([demo](/REMOVED)): ```svelte ``` ## $inspect(...).with `$inspect` returns a property `with`, which you can invoke with a callback, which will then be invoked instead of `console.log`. The first argument to the callback is either `"init"` or `"update"`; subsequent arguments are the values passed to `$inspect` ([demo](/REMOVED)): ```svelte ``` A convenient way to find the origin of some change is to pass `console.trace` to `with`: ```js // @errors: 2304 $inspect(stuff).with(console.trace); ``` ## docs/svelte/02-runes/08-$host.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $host --- When compiling a component as a custom element, the `$host` rune provides access to the host element, allowing you to (for example) dispatch custom events ([demo](/REMOVED)): ```svelte /// file: Stepper.svelte ``` ```svelte /// file: App.svelte count -= 1} onincrement={() => count += 1} >

count: {count}

``` ## docs/svelte/03-template-syntax/index.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Template syntax --- ## docs/svelte/03-template-syntax/01-basic-markup.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Basic markup --- Markup inside a Svelte component can be thought of as HTML++. ## Tags A lowercase tag, like `
`, denotes a regular HTML element. A capitalised tag or a tag that uses dot notation, such as `` or ``, indicates a _component_. ```svelte
``` ## Element attributes By default, attributes work exactly like their HTML counterparts. ```svelte
``` As in HTML, values may be unquoted. ```svelte ``` Attribute values can contain JavaScript expressions. ```svelte page {p} ``` Or they can _be_ JavaScript expressions. ```svelte ``` Boolean attributes are included on the element if their value is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) and excluded if it's [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy). All other attributes are included unless their value is [nullish](https://developer.mozilla.org/en-US/docs/Glossary/Nullish) (`null` or `undefined`). ```svelte
This div has no title attribute
``` > > > ```svelte > > ``` When the attribute name and value match (`name={name}`), they can be replaced with `{name}`. ```svelte ``` ## Component props By convention, values passed to components are referred to as _properties_ or _props_ rather than _attributes_, which are a feature of the DOM. As with elements, `name={name}` can be replaced with the `{name}` shorthand. ```svelte ``` _Spread attributes_ allow many attributes or properties to be passed to an element or component at once. An element or component can have multiple spread attributes, interspersed with regular ones. ```svelte ``` ## Events Listening to DOM events is possible by adding attributes to the element that start with `on`. For example, to listen to the `click` event, add the `onclick` attribute to a button: ```svelte ``` Event attributes are case sensitive. `onclick` listens to the `click` event, `onClick` listens to the `Click` event, which is different. This ensures you can listen to custom events that have uppercase characters in them. Because events are just attributes, the same rules as for attributes apply: - you can use the shorthand form: `` - you can spread them: `` Timing-wise, event attributes always fire after events from bindings (e.g. `oninput` always fires after an update to `bind:value`). Under the hood, some event handlers are attached directly with `addEventListener`, while others are _delegated_. When using `ontouchstart` and `ontouchmove` event attributes, the handlers are [passive](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#using_passive_listeners) for better performance. This greatly improves responsiveness by allowing the browser to scroll the document immediately, rather than waiting to see if the event handler calls `event.preventDefault()`. In the very rare cases that you need to prevent these event defaults, you should use [`on`](svelte-events#on) instead (for example inside an action). ### Event delegation To reduce memory footprint and increase performance, Svelte uses a technique called event delegation. This means that for certain events — see the list below — a single event listener at the application root takes responsibility for running any handlers on the event's path. There are a few gotchas to be aware of: - when you manually dispatch an event with a delegated listener, make sure to set the `{ bubbles: true }` option or it won't reach the application root - when using `addEventListener` directly, avoid calling `stopPropagation` or the event won't reach the application root and handlers won't be invoked. Similarly, handlers added manually inside the application root will run _before_ handlers added declaratively deeper in the DOM (with e.g. `onclick={...}`), in both capturing and bubbling phases. For these reasons it's better to use the `on` function imported from `svelte/events` rather than `addEventListener`, as it will ensure that order is preserved and `stopPropagation` is handled correctly. The following event handlers are delegated: - `beforeinput` - `click` - `change` - `dblclick` - `contextmenu` - `focusin` - `focusout` - `input` - `keydown` - `keyup` - `mousedown` - `mousemove` - `mouseout` - `mouseover` - `mouseup` - `pointerdown` - `pointermove` - `pointerout` - `pointerover` - `pointerup` - `touchend` - `touchmove` - `touchstart` ## Text expressions A JavaScript expression can be included as text by surrounding it with curly braces. ```svelte {expression} ``` Curly braces can be included in a Svelte template by using their [HTML entity](https://developer.mozilla.org/docs/Glossary/Entity) strings: `{`, `{`, or `{` for `{` and `}`, `}`, or `}` for `}`. If you're using a regular expression (`RegExp`) [literal notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#literal_notation_and_constructor), you'll need to wrap it in parentheses. ```svelte

Hello {name}!

{a} + {b} = {a + b}.

{(/^[A-Za-z ]+$/).test(value) ? x : y}
``` The expression will be stringified and escaped to prevent code injections. If you want to render HTML, use the `{@html}` tag instead. ```svelte {@html potentiallyUnsafeHtmlString} ``` ## Comments You can use HTML comments inside components. ```svelte

Hello world

``` Comments beginning with `svelte-ignore` disable warnings for the next block of markup. Usually, these are accessibility warnings; make sure that you're disabling them for a good reason. ```svelte ``` You can add a special comment starting with `@component` that will show up when hovering over the component name in other files. ````svelte

Hello, {name}

```` ## docs/svelte/03-template-syntax/02-if.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: {#if ...} --- ```svelte {#if expression}...{/if} ``` ```svelte {#if expression}...{:else if expression}...{/if} ``` ```svelte {#if expression}...{:else}...{/if} ``` Content that is conditionally rendered can be wrapped in an if block. ```svelte {#if answer === 42}

what was the question?

{/if} ``` Additional conditions can be added with `{:else if expression}`, optionally ending in an `{:else}` clause. ```svelte {#if porridge.temperature > 100}

too hot!

{:else if 80 > porridge.temperature}

too cold!

{:else}

just right!

{/if} ``` (Blocks don't have to wrap elements, they can also wrap text within elements.) ## docs/svelte/03-template-syntax/03-each.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: {#each ...} --- ```svelte {#each expression as name}...{/each} ``` ```svelte {#each expression as name, index}...{/each} ``` Iterating over values can be done with an each block. The values in question can be arrays, array-like objects (i.e. anything with a `length` property), or iterables like `Map` and `Set` — in other words, anything that can be used with `Array.from`. ```svelte

Shopping list

    {#each items as item}
  • {item.name} x {item.qty}
  • {/each}
``` An each block can also specify an _index_, equivalent to the second argument in an `array.map(...)` callback: ```svelte {#each items as item, i}
  • {i + 1}: {item.name} x {item.qty}
  • {/each} ``` ## Keyed each blocks ```svelte {#each expression as name (key)}...{/each} ``` ```svelte {#each expression as name, index (key)}...{/each} ``` If a _key_ expression is provided — which must uniquely identify each list item — Svelte will use it to diff the list when data changes, rather than adding or removing items at the end. The key can be any object, but strings and numbers are recommended since they allow identity to persist when the objects themselves change. ```svelte {#each items as item (item.id)}
  • {item.name} x {item.qty}
  • {/each} {#each items as item, i (item.id)}
  • {i + 1}: {item.name} x {item.qty}
  • {/each} ``` You can freely use destructuring and rest patterns in each blocks. ```svelte {#each items as { id, name, qty }, i (id)}
  • {i + 1}: {name} x {qty}
  • {/each} {#each objects as { id, ...rest }}
  • {id}
  • {/each} {#each items as [id, ...rest]}
  • {id}
  • {/each} ``` ## Each blocks without an item ```svelte {#each expression}...{/each} ``` ```svelte {#each expression, index}...{/each} ``` In case you just want to render something `n` times, you can omit the `as` part ([demo](/REMOVED)): ```svelte
    {#each { length: 8 }, rank} {#each { length: 8 }, file}
    {/each} {/each}
    ``` ## Else blocks ```svelte {#each expression as name}...{:else}...{/each} ``` An each block can also have an `{:else}` clause, which is rendered if the list is empty. ```svelte {#each todos as todo}

    {todo.text}

    {:else}

    No tasks today!

    {/each} ``` ## docs/svelte/03-template-syntax/04-key.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: {#key ...} --- ```svelte {#key expression}...{/key} ``` Key blocks destroy and recreate their contents when the value of an expression changes. When used around components, this will cause them to be reinstantiated and reinitialised: ```svelte {#key value} {/key} ``` It's also useful if you want a transition to play whenever a value changes: ```svelte {#key value}
    {value}
    {/key} ``` ## docs/svelte/03-template-syntax/05-await.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: {#await ...} --- ```svelte {#await expression}...{:then name}...{:catch name}...{/await} ``` ```svelte {#await expression}...{:then name}...{/await} ``` ```svelte {#await expression then name}...{/await} ``` ```svelte {#await expression catch name}...{/await} ``` Await blocks allow you to branch on the three possible states of a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — pending, fulfilled or rejected. ```svelte {#await promise}

    waiting for the promise to resolve...

    {:then value}

    The value is {value}

    {:catch error}

    Something went wrong: {error.message}

    {/await} ``` > > If the provided expression is not a `Promise`, only the `:then` branch will be rendered, including during server-side rendering. The `catch` block can be omitted if you don't need to render anything when the promise rejects (or no error is possible). ```svelte {#await promise}

    waiting for the promise to resolve...

    {:then value}

    The value is {value}

    {/await} ``` If you don't care about the pending state, you can also omit the initial block. ```svelte {#await promise then value}

    The value is {value}

    {/await} ``` Similarly, if you only want to show the error state, you can omit the `then` block. ```svelte {#await promise catch error}

    The error is {error}

    {/await} ``` > > ```svelte > {#await import('./Component.svelte') then { default: Component }} > > {/await} > ``` ## docs/svelte/03-template-syntax/06-snippet.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: {#snippet ...} --- ```svelte {#snippet name()}...{/snippet} ``` ```svelte {#snippet name(param1, param2, paramN)}...{/snippet} ``` Snippets, and [render tags](@render), are a way to create reusable chunks of markup inside your components. Instead of writing duplicative code like [this](/REMOVED)... ```svelte {#each images as image} {#if image.href}
    {image.caption}
    {image.caption}
    {:else}
    {image.caption}
    {image.caption}
    {/if} {/each} ``` ...you can write [this](/REMOVED): ```svelte {#snippet figure(image)}
    {image.caption}
    {image.caption}
    {/snippet} {#each images as image} {#if image.href} {@render figure(image)} {:else} {@render figure(image)} {/if} {/each} ``` Like function declarations, snippets can have an arbitrary number of parameters, which can have default values, and you can destructure each parameter. You cannot use rest parameters, however. ## Snippet scope Snippets can be declared anywhere inside your component. They can reference values declared outside themselves, for example in the ` {#snippet hello(name)}

    hello {name}! {message}!

    {/snippet} {@render hello('alice')} {@render hello('bob')} ``` ...and they are 'visible' to everything in the same lexical scope (i.e. siblings, and children of those siblings): ```svelte
    {#snippet x()} {#snippet y()}...{/snippet} {@render y()} {/snippet} {@render y()}
    {@render x()} ``` Snippets can reference themselves and each other ([demo](/REMOVED)): ```svelte {#snippet blastoff()} 🚀 {/snippet} {#snippet countdown(n)} {#if n > 0} {n}... {@render countdown(n - 1)} {:else} {@render blastoff()} {/if} {/snippet} {@render countdown(10)} ``` ## Passing snippets to components Within the template, snippets are values just like any other. As such, they can be passed to components as props ([demo](/REMOVED)): ```svelte {#snippet header()} fruit qty price total {/snippet} {#snippet row(d)} {d.name} {d.qty} {d.price} {d.qty * d.price} {/snippet} ``` Think about it like passing content instead of data to a component. The concept is similar to slots in web components. As an authoring convenience, snippets declared directly _inside_ a component implicitly become props _on_ the component ([demo](/REMOVED)): ```svelte
    {#snippet header()} {/snippet} {#snippet row(d)} {/snippet}
    fruit qty price total{d.name} {d.qty} {d.price} {d.qty * d.price}
    ``` Any content inside the component tags that is _not_ a snippet declaration implicitly becomes part of the `children` snippet ([demo](/REMOVED)): ```svelte ``` ```svelte ``` You can declare snippet props as being optional. You can either use optional chaining to not render anything if the snippet isn't set... ```svelte {@render children?.()} ``` ...or use an `#if` block to render fallback content: ```svelte {#if children} {@render children()} {:else} fallback content {/if} ``` ## Typing snippets Snippets implement the `Snippet` interface imported from `'svelte'`: ```svelte ``` With this change, red squigglies will appear if you try and use the component without providing a `data` prop and a `row` snippet. Notice that the type argument provided to `Snippet` is a tuple, since snippets can have multiple parameters. We can tighten things up further by declaring a generic, so that `data` and `row` refer to the same type: ```svelte ``` ## Exporting snippets Snippets declared at the top level of a `.svelte` file can be exported from a ` {#snippet add(a, b)} {a} + {b} = {a + b} {/snippet} ``` > This requires Svelte 5.5.0 or newer ## Programmatic snippets Snippets can be created programmatically with the [`createRawSnippet`](svelte#createRawSnippet) API. This is intended for advanced use cases. ## Snippets and slots In Svelte 4, content can be passed to components using [slots](legacy-slots). Snippets are more powerful and flexible, and as such slots are deprecated in Svelte 5. ## docs/svelte/03-template-syntax/07-@render.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: {@render ...} --- To render a [snippet](snippet), use a `{@render ...}` tag. ```svelte {#snippet sum(a, b)}

    {a} + {b} = {a + b}

    {/snippet} {@render sum(1, 2)} {@render sum(3, 4)} {@render sum(5, 6)} ``` The expression can be an identifier like `sum`, or an arbitrary JavaScript expression: ```svelte {@render (cool ? coolSnippet : lameSnippet)()} ``` ## Optional snippets If the snippet is potentially undefined — for example, because it's an incoming prop — then you can use optional chaining to only render it when it _is_ defined: ```svelte {@render children?.()} ``` Alternatively, use an [`{#if ...}`](if) block with an `:else` clause to render fallback content: ```svelte {#if children} {@render children()} {:else}

    fallback content

    {/if} ``` ## docs/svelte/03-template-syntax/08-@html.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: {@html ...} --- To inject raw HTML into your component, use the `{@html ...}` tag: ```svelte
    {@html content}
    ``` The expression should be valid standalone HTML — this will not work, because `
    ` is not valid HTML: ```svelte {@html '
    '}content{@html '
    '} ``` It also will not compile Svelte code. ## Styling Content rendered this way is 'invisible' to Svelte and as such will not receive [scoped styles](scoped-styles) — in other words, this will not work, and the `a` and `img` styles will be regarded as unused: ```svelte
    {@html content}
    ``` Instead, use the `:global` modifier to target everything inside the `
    `: ```svelte ``` ## docs/svelte/03-template-syntax/09-@const.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: {@const ...} --- The `{@const ...}` tag defines a local constant. ```svelte {#each boxes as box} {@const area = box.width * box.height} {box.width} * {box.height} = {area} {/each} ``` `{@const}` is only allowed as an immediate child of a block — `{#if ...}`, `{#each ...}`, `{#snippet ...}` and so on — or a ``. ## docs/svelte/03-template-syntax/10-@debug.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: {@debug ...} --- The `{@debug ...}` tag offers an alternative to `console.log(...)`. It logs the values of specific variables whenever they change, and pauses code execution if you have devtools open. ```svelte {@debug user}

    Hello {user.firstname}!

    ``` `{@debug ...}` accepts a comma-separated list of variable names (not arbitrary expressions). ```svelte {@debug user} {@debug user1, user2, user3} {@debug user.firstname} {@debug myArray[0]} {@debug !isReady} {@debug typeof user === 'object'} ``` The `{@debug}` tag without any arguments will insert a `debugger` statement that gets triggered when _any_ state changes, as opposed to the specified variables. ## docs/svelte/03-template-syntax/11-bind.md --- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: bind: --- Data ordinarily flows down, from parent to child. The `bind:` directive allows data to flow the other way, from child to parent. The general syntax is `bind:property={expression}`, where `expression` is an _lvalue_ (i.e. a variable or an object property). When the expression is an identifier with the same name as the property, we can omit the expression — in other words these are equivalent: ```svelte ``` Svelte creates an event listener that updates the bound value. If an element already has a listener for the same event, that listener will be fired before the bound value is updated. Most bindings are _two-way_, meaning that changes to the value will affect the element and vice versa. A few bindings are _readonly_, meaning that changing their value will have no effect on the element. ## Function bindings You can also use `bind:property={get, set}`, where `get` and `set` are functions, allowing you to perform validation and transformation: ```svelte value, (v) => value = v.toLowerCase()} /> ``` In the case of readonly bindings like [dimension bindings](#Dimensions), the `get` value should be `null`: ```svelte
    ...
    ``` > Function bindings are available in Svelte 5.9.0 and newer. ## `` A `bind:value` directive on an `` element binds the input's `value` property: ```svelte

    {message}

    ``` In the case of a numeric input (`type="number"` or `type="range"`), the value will be coerced to a number ([demo](/REMOVED)): ```svelte

    {a} + {b} = {a + b}

    ``` If the input is empty or invalid (in the case of `type="number"`), the value is `undefined`. Since 5.6.0, if an `` has a `defaultValue` and is part of a form, it will revert to that value instead of the empty string when the form is reset. Note that for the initial render the value of the binding takes precedence unless it is `null` or `undefined`. ```svelte
    ``` > Use reset buttons sparingly, and ensure that users won't accidentally click them while trying to submit the form. ## `` Checkbox and radio inputs can be bound with `bind:checked`: ```svelte ``` Since 5.6.0, if an `` has a `defaultChecked` attribute and is part of a form, it will revert to that value instead of `false` when the form is reset. Note that for the initial render the value of the binding takes precedence unless it is `null` or `undefined`. ```svelte
    ``` ## `` Inputs that work together can use `bind:group`. ```svelte ``` ## `` On `` elements with `type="file"`, you can use `bind:files` to get the [`FileList` of selected files](https://developer.mozilla.org/en-US/docs/Web/API/FileList). When you want to update the files programmatically, you always need to use a `FileList` object. Currently `FileList` objects cannot be constructed directly, so you need to create a new [`DataTransfer`](https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer) object and get `files` from there. ```svelte ``` `FileList` objects also cannot be modified, so if you want to e.g. delete a single file from the list, you need to create a new `DataTransfer` object and add the files you want to keep. ## `` value binding corresponds to the `value` property on the selected ` ``` When the value of an ` ``` ## `