`), and cannot be observed with a `ResizeObserver`. You will need to change the `display` style of these elements to something else, such as `inline-block`. Note that CSS transformations do not trigger `ResizeObserver` callbacks. ## bind:this ```svelte bind:this={dom_node} ``` To get a reference to a DOM node, use `bind:this`. The value will be `undefined` until the component is mounted — in other words, you should read it inside an effect or an event handler, but not during component initialisation: ```svelte ``` Components also support `bind:this`, allowing you to interact with component instances programmatically. ```svelte cart.empty()}> Empty shopping cart ``` ```svelte ``` > [!NOTE] In case of using [the function bindings](#Function-bindings), the getter is required to ensure that the correct value is nullified on component or element destruction. ## bind:_property_ for components ```svelte bind:property={variable} ``` You can bind to component props using the same syntax as for elements. ```svelte ``` While Svelte props are reactive without binding, that reactivity only flows downward into the component by default. Using `bind:property` allows changes to the property from within the component to flow back up out of the component. To mark a property as bindable, use the [`$bindable`]($bindable) rune: ```svelte ``` Declaring a property as bindable means it _can_ be used using `bind:`, not that it _must_ be used using `bind:`. Bindable properties can have a fallback value: ```svelte ``` This fallback value _only_ applies when the property is _not_ bound. When the property is bound and a fallback value is present, the parent is expected to provide a value other than `undefined`, else a runtime error is thrown. This prevents hard-to-reason-about situations where it's unclear which value should apply. --- title: use: --- > [!NOTE] > In Svelte 5.29 and newer, consider using [attachments](@attach) instead, as they are more flexible and composable. Actions are functions that are called when an element is mounted. They are added with the `use:` directive, and will typically use an `$effect` so that they can reset any state when the element is unmounted: ```svelte ...
``` An action can be called with an argument: ```svelte ...
``` The action is only called once (but not during server-side rendering) — it will _not_ run again if the argument changes. > [!LEGACY] > Prior to the `$effect` rune, actions could return an object with `update` and `destroy` methods, where `update` would be called with the latest value of the argument if it changed. Using effects is preferred. ## Typing The `Action` interface receives three optional type arguments — a node type (which can be `Element`, if the action applies to everything), a parameter, and any custom event handlers created by the action: ```svelte ...
``` --- title: transition: --- A _transition_ is triggered by an element entering or leaving the DOM as a result of a state change. When a block (such as an `{#if ...}` block) is transitioning out, all elements inside it, including those that do not have their own transitions, are kept in the DOM until every transition in the block has been completed. The `transition:` directive indicates a _bidirectional_ transition, which means it can be smoothly reversed while the transition is in progress. ```svelte visible = !visible}>toggle {#if visible} fades in and out
{/if} ``` ## Local vs global Transitions are local by default. Local transitions only play when the block they belong to is created or destroyed, _not_ when parent blocks are created or destroyed. ```svelte {#if x} {#if y} fades in and out only when y changes
fades in and out when x or y change
{/if} {/if} ``` ## Built-in transitions A selection of built-in transitions can be imported from the [`svelte/transition`](svelte-transition) module. ## Transition parameters Transitions can have parameters. (The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.) ```svelte {#if visible} fades in and out over two seconds
{/if} ``` ## Custom transition functions ```js /// copy: false // @noErrors transition = (node: HTMLElement, params: any, options: { direction: 'in' | 'out' | 'both' }) => { delay?: number, duration?: number, easing?: (t: number) => number, css?: (t: number, u: number) => string, tick?: (t: number, u: number) => void } ``` Transitions can use custom functions. If the returned object has a `css` function, Svelte will generate keyframes for a [web animation](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API). The `t` argument passed to `css` is a value between `0` and `1` after the `easing` function has been applied. _In_ transitions run from `0` to `1`, _out_ transitions run from `1` to `0` — in other words, `1` is the element's natural state, as though no transition had been applied. The `u` argument is equal to `1 - t`. The function is called repeatedly _before_ the transition begins, with different `t` and `u` arguments. ```svelte {#if visible} whooshes in
{/if} ``` A custom transition function can also return a `tick` function, which is called _during_ the transition with the same `t` and `u` arguments. > [!NOTE] If it's possible to use `css` instead of `tick`, do so — web animations can run off the main thread, preventing jank on slower devices. ```svelte {#if visible} The quick brown fox jumps over the lazy dog
{/if} ``` If a transition returns a function instead of a transition object, the function will be called in the next microtask. This allows multiple transitions to coordinate, making [crossfade effects](/tutorial/deferred-transitions) possible. Transition functions also receive a third argument, `options`, which contains information about the transition. Available values in the `options` object are: - `direction` - one of `in`, `out`, or `both` depending on the type of transition ## Transition events An element with transitions will dispatch the following events in addition to any standard DOM events: - `introstart` - `introend` - `outrostart` - `outroend` ```svelte {#if visible} (status = 'intro started')} onoutrostart={() => (status = 'outro started')} onintroend={() => (status = 'intro ended')} onoutroend={() => (status = 'outro ended')} > Flies in and out
{/if} ``` --- title: in: and out: --- The `in:` and `out:` directives are identical to [`transition:`](transition), except that the resulting transitions are not bidirectional — an `in` transition will continue to 'play' alongside the `out` transition, rather than reversing, if the block is outroed while the transition is in progress. If an out transition is aborted, transitions will restart from scratch. ```svelte visible {#if visible} flies in, fades out
{/if} ``` --- title: animate: --- An animation is triggered when the contents of a [keyed each block](each#Keyed-each-blocks) are re-ordered. Animations do not run when an element is added or removed, only when the index of an existing data item within the each block changes. Animate directives must be on an element that is an _immediate_ child of a keyed each block. Animations can be used with Svelte's [built-in animation functions](svelte-animate) or [custom animation functions](#Custom-animation-functions). ```svelte {#each list as item, index (item)} {item} {/each} ``` ## Animation Parameters As with actions and transitions, animations can have parameters. (The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.) ```svelte {#each list as item, index (item)} {item} {/each} ``` ## Custom animation functions ```js /// copy: false // @noErrors animation = (node: HTMLElement, { from: DOMRect, to: DOMRect } , params: any) => { delay?: number, duration?: number, easing?: (t: number) => number, css?: (t: number, u: number) => string, tick?: (t: number, u: number) => void } ``` Animations can use custom functions that provide the `node`, an `animation` object and any `parameters` as arguments. The `animation` parameter is an object containing `from` and `to` properties each containing a [DOMRect](https://developer.mozilla.org/en-US/docs/Web/API/DOMRect#Properties) describing the geometry of the element in its `start` and `end` positions. The `from` property is the DOMRect of the element in its starting position, and the `to` property is the DOMRect of the element in its final position after the list has been reordered and the DOM updated. If the returned object has a `css` method, Svelte will create a [web animation](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API) that plays on the element. The `t` argument passed to `css` is a value that goes from `0` and `1` after the `easing` function has been applied. The `u` argument is equal to `1 - t`. The function is called repeatedly _before_ the animation begins, with different `t` and `u` arguments. ```svelte {#each list as item, index (item)} {item}
{/each} ``` A custom animation function can also return a `tick` function, which is called _during_ the animation with the same `t` and `u` arguments. > [!NOTE] If it's possible to use `css` instead of `tick`, do so — web animations can run off the main thread, preventing jank on slower devices. ```svelte {#each list as item, index (item)} {item}
{/each} ``` --- title: style: --- The `style:` directive provides a shorthand for setting multiple styles on an element. ```svelte ...
...
``` The value can contain arbitrary expressions: ```svelte ...
``` The shorthand form is allowed: ```svelte ...
``` Multiple styles can be set on a single element: ```svelte ...
``` To mark a style as important, use the `|important` modifier: ```svelte ...
``` When `style:` directives are combined with `style` attributes, the directives will take precedence, even over `!important` properties: ```svelte This will be red
This will still be red
``` --- title: class --- There are two ways to set classes on elements: the `class` attribute, and the `class:` directive. ## Attributes Primitive values are treated like any other attribute: ```svelte ...
``` > [!NOTE] > For historical reasons, falsy values (like `false` and `NaN`) are stringified (`class="false"`), though `class={undefined}` (or `null`) cause the attribute to be omitted altogether. In a future version of Svelte, all falsy values will cause `class` to be omitted. ### Objects and arrays Since Svelte 5.16, `class` can be an object or array, and is converted to a string using [clsx](https://github.com/lukeed/clsx). If the value is an object, the truthy keys are added: ```svelte ...
``` If the value is an array, the truthy values are combined: ```svelte ...
``` Note that whether we're using the array or object form, we can set multiple classes simultaneously with a single condition, which is particularly useful if you're using things like Tailwind. Arrays can contain arrays and objects, and clsx will flatten them. This is useful for combining local classes with props, for example: ```svelte {@render props.children?.()} ``` The user of this component has the same flexibility to use a mixture of objects, arrays and strings: ```svelte useTailwind = true} class={{ 'bg-blue-700 sm:w-1/2': useTailwind }} > Accept the inevitability of Tailwind ``` Since Svelte 5.19, Svelte also exposes the `ClassValue` type, which is the type of value that the `class` attribute on elements accept. This is useful if you want to use a type-safe class name in component props: ```svelte ...
``` ## The `class:` directive Prior to Svelte 5.16, the `class:` directive was the most convenient way to set classes on elements conditionally. ```svelte ...
...
``` As with other directives, we can use a shorthand when the name of the class coincides with the value: ```svelte ...
``` > [!NOTE] Unless you're using an older version of Svelte, consider avoiding `class:`, since the attribute is more powerful and composable. --- title: await --- As of Svelte 5.36, you can use the `await` keyword inside your components in three places where it was previously unavailable: - at the top level of your component's ` {a} + {b} = {await add(a, b)}
``` ...if you increment `a`, the contents of the `` will _not_ immediately update to read this — ```html
2 + 2 = 3
``` — instead, the text will update to `2 + 2 = 4` when `add(a, b)` resolves. Updates can overlap — a fast update will be reflected in the UI while an earlier slow update is still ongoing. ## Concurrency Svelte will do as much asynchronous work as it can in parallel. For example if you have two `await` expressions in your markup... ```svelte {await one()}
{await two()}
``` ...both functions will run at the same time, as they are independent expressions, even though they are _visually_ sequential. This does not apply to sequential `await` expressions inside your ` { pending?.commit(); pending = null; // in case `pending` didn't exist // (if it did, this is a no-op) open = true; }} >open menu {#if open} open = false} /> {/if} ``` ## Caveats As an experimental feature, the details of how `await` is handled (and related APIs like `$effect.pending()`) are subject to breaking changes outside of a semver major release, though we intend to keep such changes to a bare minimum. ## Breaking changes Effects run in a slightly different order when the `experimental.async` option is `true`. Specifically, _block_ effects like `{#if ...}` and `{#each ...}` now run before an `$effect.pre` or `beforeUpdate` in the same component, which means that in [very rare situations](/playground/untitled?#H4sIAAAAAAAAE22R3VLDIBCFX2WLvUhnTHsf0zre-Q7WmfwtFV2BgU1rJ5N3F0jaOuoVcPbw7VkYhK4_URTiGYkMnIyjDjLsFGO3EvdCKkIvipdB8NlGXxSCPt96snbtj0gctab2-J_eGs2oOWBE6VunLO_2es-EDKZ5x5ZhC0vPNWM2gHXGouNzAex6hHH1cPHil_Lsb95YT9VQX6KUAbS2DrNsBdsdDFHe8_XSYjH1SrhELTe3MLpsemajweiWVPuxHSbKNd-8eQTdE0EBf4OOaSg2hwNhhE_ABB_ulJzjj9FULvIcqgm5vnAqUB7wWFMfhuugQWkcAr8hVD-mq8D12kOep24J_IszToOXdveGDsuNnZwbJUNlXsKnhJdhUcTo42s41YpOSneikDV5HL8BktM6yRcCAAA=) it is possible to update a block that should no longer exist, but only if you update state inside an effect, [which you should avoid]($effect#When-not-to-use-$effect). --- title: Template syntax --- --- title: Scoped styles --- Svelte components can include a ` ``` ## Specificity Each scoped selector receives a [specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity) increase of 0-1-0, as a result of the scoping class (e.g. `.svelte-123xyz`) being added to the selector. This means that (for example) a `p` selector defined in a component will take precedence over a `p` selector defined in a global stylesheet, even if the global stylesheet is loaded later. In some cases, the scoping class must be added to a selector multiple times, but after the first occurrence it is added with `:where(.svelte-xyz123)` in order to not increase specificity further. ## Scoped keyframes If a component defines `@keyframes`, the name is scoped to the component using the same hashing approach. Any `animation` rules in the component will be similarly adjusted: ```svelte ``` --- title: Global styles --- ## :global(...) To apply styles to a single selector globally, use the `:global(...)` modifier: ```svelte ``` If you want to make @keyframes that are accessible globally, you need to prepend your keyframe names with `-global-`. The `-global-` part will be removed when compiled, and the keyframe will then be referenced using just `my-animation-name` elsewhere in your code. ```svelte ``` ## :global To apply styles to a group of selectors globally, create a `:global {...}` block: ```svelte ``` > [!NOTE] The second example above could also be written as an equivalent `.a :global .b .c .d` selector, where everything after the `:global` is unscoped, though the nested form is preferred. --- title: Custom properties --- You can pass CSS custom properties — both static and dynamic — to components: ```svelte ``` The above code essentially desugars to this: ```svelte ``` For an SVG element, it would use `` instead: ```svelte ``` Inside the component, we can read these custom properties (and provide fallback values) using [`var(...)`](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties): ```svelte ``` You don't _have_ to specify the values directly on the component; as long as the custom properties are defined on a parent element, the component can use them. It's common to define custom properties on the `:root` element in a global stylesheet so that they apply to your entire application. > [!NOTE] While the extra element will not affect layout, it _will_ affect any CSS selectors that (for example) use the `>` combinator to target an element directly inside the component's container. --- title: Nested ``` --- title: Styling --- --- title: --- ```svelte ... ``` > [!NOTE] > This feature was added in 5.3.0 Boundaries allow you to 'wall off' parts of your app, so that you can: - provide UI that should be shown when [`await`](await-expressions) expressions are first resolving - handle errors that occur during rendering or while running effects, and provide UI that should be rendered when an error happens If a boundary handles an error (with a `failed` snippet or `onerror` handler, or both) its existing content will be removed. > [!NOTE] Errors occurring outside the rendering process (for example, in event handlers or after a `setTimeout` or async work) are _not_ caught by error boundaries. ## Properties For the boundary to do anything, one or more of the following must be provided. ### `pending` This snippet will be shown when the boundary is first created, and will remain visible until all the [`await`](await-expressions) expressions inside the boundary have resolved ([demo](/playground/untitled#H4sIAAAAAAAAE21QQW6DQAz8ytY9BKQVpFdKkPqDHnorPWzAaSwt3tWugUaIv1eE0KpKD5as8YxnNBOw6RAKKOOAVrA4up5bEy6VGknOyiO3xJ8qMnmPAhpOZDFC8T6BXPyiXADQ258X77P1FWg4moj_4Y1jQZZ49W0CealqruXUcyPkWLVozQXbZDC2R606spYiNo7bqA7qab_fp2paFLUElD6wYhzVa3AdRUySgNHZAVN1qDZaLRHljTp0vSTJ9XJjrSbpX5f0eZXN6zLXXOa_QfmurIVU-moyoyH5ib87o7XuYZfOZe6vnGWmx1uZW7lJOq9upa-sMwuUZdkmmfIbfQ1xZwwaBL8ECgk9zh8axJAdiVsoTsZGnL8Bg4tX_OMBAAA=)): ```svelte {await delayed('hello!')}
{#snippet pending()} loading...
{/snippet} ``` The `pending` snippet will _not_ be shown for subsequent async updates — for these, you can use [`$effect.pending()`]($effect#$effect.pending). > [!NOTE] In the [playground](/playground), your app is rendered inside a boundary with an empty pending snippet, so that you can use `await` without having to create one. ### `failed` If a `failed` snippet is provided, it will be rendered when an error is thrown inside the boundary, with the `error` and a `reset` function that recreates the contents ([demo](/playground/hello-world#H4sIAAAAAAAAE3VRy26DMBD8lS2tFCIh6JkAUlWp39Cq9EBg06CAbdlLArL87zWGKk8ORnhmd3ZnrD1WtOjFXqKO2BDGW96xqpBD5gXerm5QefG39mgQY9EIWHxueRMinLosti0UPsJLzggZKTeilLWgLGc51a3gkuCjKQ7DO7cXZotgJ3kLqzC6hmex1SZnSXTWYHcrj8LJjWTk0PHoZ8VqIdCOKayPykcpuQxAokJaG1dGybYj4gw4K5u6PKTasSbjXKgnIDlA8VvUdo-pzonraBY2bsH7HAl78mKSHZpgIcuHjq9jXSpZSLixRlveKYQUXhQVhL6GPobXAAb7BbNeyvNUs4qfRg3OnELLj5hqH9eQZqCnoBwR9lYcQxuVXeBzc8kMF8yXY4yNJ5oGiUzP_aaf_waTRGJib5_Ad3P_vbCuaYxzeNpbU0eUMPAOKh7Yw1YErgtoXyuYlPLzc10_xo_5A91zkQL_AgAA)): ```svelte {#snippet failed(error, reset)} oops! try again {/snippet} ``` > [!NOTE] > As with [snippets passed to components](snippet#Passing-snippets-to-components), the `failed` snippet can be passed explicitly as a property... > > ```svelte > ... > ``` > > ...or implicitly by declaring it directly inside the boundary, as in the example above. ### `onerror` If an `onerror` function is provided, it will be called with the same two `error` and `reset` arguments. This is useful for tracking the error with an error reporting service... ```svelte report(e)}> ... ``` ...or using `error` and `reset` outside the boundary itself: ```svelte {#if error} { error = null; reset(); }}> oops! try again {/if} ``` If an error occurs inside the `onerror` function (or if you rethrow the error), it will be handled by a parent boundary if such exists. --- title: --- ```svelte ``` ```svelte ``` The `` element allows you to add event listeners to the `window` object without worrying about removing them when the component is destroyed, or checking for the existence of `window` when server-side rendering. This element may only appear at the top level of your component — it cannot be inside a block or element. ```svelte ``` You can also bind to the following properties: - `innerWidth` - `innerHeight` - `outerWidth` - `outerHeight` - `scrollX` - `scrollY` - `online` — an alias for `window.navigator.onLine` - `devicePixelRatio` All except `scrollX` and `scrollY` are readonly. ```svelte ``` > [!NOTE] Note that the page will not be scrolled to the initial value to avoid accessibility issues. Only subsequent changes to the bound variable of `scrollX` and `scrollY` will cause scrolling. If you have a legitimate reason to scroll when the component is rendered, call `scrollTo()` in an `$effect`. --- title: --- ```svelte ``` ```svelte ``` Similarly to ``, this element allows you to add listeners to events on `document`, such as `visibilitychange`, which don't fire on `window`. It also lets you use [actions](use) on `document`. As with ``, this element may only appear the top level of your component and must never be inside a block or element. ```svelte ``` You can also bind to the following properties: - `activeElement` - `fullscreenElement` - `pointerLockElement` - `visibilityState` All are readonly. --- title: --- ```svelte ``` Similarly to ``, this element allows you to add listeners to events on `document.body`, such as `mouseenter` and `mouseleave`, which don't fire on `window`. It also lets you use [actions](use) on the `` element. As with `` and ``, this element may only appear at the top level of your component and must never be inside a block or element. ```svelte ``` --- title: --- ```svelte ... ``` This element makes it possible to insert elements into `document.head`. During server-side rendering, `head` content is exposed separately to the main `body` content. As with ``, `` and ``, this element may only appear at the top level of your component and must never be inside a block or element. ```svelte Hello world! ``` --- title: --- ```svelte ``` The `` element lets you render an element that is unknown at author time, for example because it comes from a CMS. Any properties and event listeners present will be applied to the element. The only supported binding is `bind:this`, since Svelte's built-in bindings do not work with generic elements. If `this` has a nullish value, the element and its children will not be rendered. If `this` is the name of a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element) (e.g., `br`) and `` has child elements, a runtime error will be thrown in development mode: ```svelte This text cannot appear inside an hr element ``` Svelte tries its best to infer the correct namespace from the element's surroundings, but it's not always possible. You can make it explicit with an `xmlns` attribute: ```svelte ``` `this` needs to be a valid DOM element tag, things like `#text` or `svelte:head` will not work. --- title: --- ```svelte ``` The `` element provides a place to specify per-component compiler options, which are detailed in the [compiler section](svelte-compiler#compile). The possible options are: - `runes={true}` — forces a component into _runes mode_ (see the [Legacy APIs](legacy-overview) section) - `runes={false}` — forces a component into _legacy mode_ - `namespace="..."` — the namespace where this component will be used, can be "html" (the default), "svg" or "mathml" - `customElement={...}` — the [options](custom-elements#Component-options) to use when compiling this component as a custom element. If a string is passed, it is used as the `tag` option - `css="injected"` — the component will inject its styles inline: During server-side rendering, it's injected as a ` ``` In Svelte 3/4 using `$$props` and `$$restProps` creates a modest performance penalty, so they should only be used when needed. --- title: on: --- In runes mode, event handlers are just like any other attribute or prop. In legacy mode, we use the `on:` directive: ```svelte count: {count} ``` Handlers can be declared inline with no performance penalty: ```svelte (count += 1)}> count: {count} ``` Add _modifiers_ to element event handlers with the `|` character. ```svelte ``` The following modifiers are available: - `preventDefault` — calls `event.preventDefault()` before running the handler - `stopPropagation` — calls `event.stopPropagation()`, preventing the event reaching the next element - `stopImmediatePropagation` — calls `event.stopImmediatePropagation()`, preventing other listeners of the same event from being fired. - `passive` — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so) - `nonpassive` — explicitly set `passive: false` - `capture` — fires the handler during the _capture_ phase instead of the _bubbling_ phase - `once` — remove the handler after the first time it runs - `self` — only trigger handler if `event.target` is the element itself - `trusted` — only trigger handler if `event.isTrusted` is `true`. I.e. if the event is triggered by a user action. Modifiers can be chained together, e.g. `on:click|once|capture={...}`. If the `on:` directive is used without a value, the component will _forward_ the event, meaning that a consumer of the component can listen for it. ```svelte The component itself will emit the click event ``` It's possible to have multiple event listeners for the same event: ```svelte clicks: {count} ``` ## Component events Components can dispatch events by creating a _dispatcher_ when they are initialised: ```svelte dispatch('decrement')}>decrement dispatch('increment')}>increment ``` `dispatch` creates a [`CustomEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent). If a second argument is provided, it becomes the `detail` property of the event object. A consumer of this component can listen for the dispatched events: ```svelte n -= 1} on:increment={() => n += 1} /> n: {n}
``` Component events do not bubble — a parent component can only listen for events on its immediate children. Other than `once`, modifiers are not valid on component event handlers. > [!NOTE] > If you're planning an eventual migration to Svelte 5, use callback props instead. This will make upgrading easier as `createEventDispatcher` is deprecated: > > ```svelte > > > > decrement > increment > ``` --- title: --- In Svelte 5, content can be passed to components in the form of [snippets](snippet) and rendered using [render tags](@render). In legacy mode, content inside component tags is considered _slotted content_, which can be rendered by the component using a `` element: ```svelte This is some slotted content ``` ```svelte
``` > [!NOTE] If you want to render a regular `` element, you can use ` `. ## Named slots A component can have _named_ slots in addition to the default slot. On the parent side, add a `slot="..."` attribute to an element, component or [``](legacy-svelte-fragment) directly inside the component tags. ```svelte {#if open} This is some slotted content ++++++ open = false}> close +++
+++ {/if} ``` On the child side, add a corresponding `` element: ```svelte
+++ +++ ``` ## Fallback content If no slotted content is provided, a component can define fallback content by putting it inside the `` element: ```svelte This will be rendered if no slotted content is provided ``` ## Passing data to slotted content Slots can be rendered zero or more times and can pass values _back_ to the parent using props. The parent exposes the values to the slot template using the `let:` directive. ```svelte {#each items as data} {/each} ``` ```svelte {processed.text}
``` The usual shorthand rules apply — `let:item` is equivalent to `let:item={item}`, and `` is equivalent to ``. Named slots can also expose values. The `let:` directive goes on the element with the `slot` attribute. ```svelte {#each items as item} {/each} ``` ```svelte {item.text}
Copyright (c) 2019 Svelte Industries
``` --- title: $$slots --- In runes mode, we know which [snippets](snippet) were provided to a component, as they're just normal props. In legacy mode, the way to know if content was provided for a given slot is with the `$$slots` object, whose keys are the names of the slots passed into the component by the parent. ```svelte {#if $$slots.description}
{/if} ``` ```svelte Blog Post Title ``` --- title: --- The `` element allows you to place content in a [named slot](legacy-slots) without wrapping it in a container DOM element. This keeps the flow layout of your document intact. ```svelte No header was provided Some content between header and footer
``` ```svelte Hello All rights reserved.
Copyright (c) 2019 Svelte Industries
``` > [!NOTE] > In Svelte 5+, this concept is obsolete, as snippets don't create a wrapping element --- title: --- In runes mode, `` will re-render if the value of `MyComponent` changes. See the [Svelte 5 migration guide](/docs/svelte/v5-migration-guide#svelte:component-is-no-longer-necessary) for an example. In legacy mode, it won't — we must use ``, which destroys and recreates the component instance when the value of its `this` expression changes: ```svelte ``` If `this` is falsy, no component is rendered. --- title: --- The `` element allows a component to include itself, recursively. It cannot appear at the top level of your markup; it must be inside an if or each block or passed to a component's slot to prevent an infinite loop. ```svelte {#if count > 0} counting down... {count}
{:else} lift-off!
{/if} ``` > [!NOTE] > This concept is obsolete, as components can import themselves: > ```svelte > > > > {#if count > 0} > counting down... {count}
> > {:else} > lift-off!
> {/if} > ``` --- title: Imperative component API --- In Svelte 3 and 4, the API for interacting with a component is different than in Svelte 5. Note that this page does _not_ apply to legacy mode components in a Svelte 5 application. ## Creating a component ```ts // @noErrors const component = new Component(options); ``` A client-side component — that is, a component compiled with `generate: 'dom'` (or the `generate` option left unspecified) is a JavaScript class. ```ts // @noErrors import App from './App.svelte'; const app = new App({ target: document.body, props: { // assuming App.svelte contains something like // `export let answer`: answer: 42 } }); ``` The following initialisation options can be provided: | option | default | description | | --------- | ----------- | ---------------------------------------------------------------------------------------------------- | | `target` | **none** | An `HTMLElement` or `ShadowRoot` to render to. This option is required | | `anchor` | `null` | A child of `target` to render the component immediately before | | `props` | `{}` | An object of properties to supply to the component | | `context` | `new Map()` | A `Map` of root-level context key-value pairs to supply to the component | | `hydrate` | `false` | See below | | `intro` | `false` | If `true`, will play transitions on initial render, rather than waiting for subsequent state changes | Existing children of `target` are left where they are. The `hydrate` option instructs Svelte to upgrade existing DOM (usually from server-side rendering) rather than creating new elements. It will only work if the component was compiled with the [`hydratable: true` option](/docs/svelte-compiler#compile). Hydration of `` elements only works properly if the server-side rendering code was also compiled with `hydratable: true`, which adds a marker to each element in the `` so that the component knows which elements it's responsible for removing during hydration. Whereas children of `target` are normally left alone, `hydrate: true` will cause any children to be removed. For that reason, the `anchor` option cannot be used alongside `hydrate: true`. The existing DOM doesn't need to match the component — Svelte will 'repair' the DOM as it goes. ```ts /// file: index.js // @noErrors import App from './App.svelte'; const app = new App({ target: document.querySelector('#server-rendered-html'), hydrate: true }); ``` > [!NOTE] > In Svelte 5+, use [`mount`](svelte#mount) instead ## `$set` ```ts // @noErrors component.$set(props); ``` Programmatically sets props on an instance. `component.$set({ x: 1 })` is equivalent to `x = 1` inside the component's `