--- 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 ``` ## <script> A ` ``` You can specify a default initial value for a prop. It will be used if the component's consumer doesn't specify the prop on the component (or if its initial value is `undefined`) when instantiating the component. Note that whenever a prop is removed by the consumer, its value is set to `undefined` rather than the initial value. In development mode (see the [compiler options](/docs/svelte-compiler#svelte-compile)), a warning will be printed if no default initial value is provided and the consumer does not specify a value. To squelch this warning, ensure that a default initial value is specified, even if it is `undefined`. ```svelte ``` If you export a `const`, `class` or `function`, it is readonly from outside the component. Functions are valid prop values, however, as shown below. ```svelte ``` Readonly props can be accessed as properties on the element, tied to the component using [`bind:this` syntax](/docs/component-directives#bind-this). You can use reserved words as prop names. ```svelte ``` ### 2. Assignments are 'reactive' To change component state and trigger a re-render, just assign to a locally declared variable. Update expressions (`count += 1`) and property assignments (`obj.x = y`) have the same effect. ```svelte ``` Because Svelte's reactivity is based on assignments, using array methods like `.push()` and `.splice()` won't automatically trigger updates. A subsequent assignment is required to trigger the update. This and more details can also be found in the [tutorial](/tutorial/updating-arrays-and-objects). ```svelte ``` Svelte's ` ``` ### 3. `$:` marks a statement as reactive --- Any top-level statement (i.e. not inside a block or a function) can be made reactive by prefixing it with the `$:` [JS label syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label). Reactive statements run after other script code and before the component markup is rendered, whenever the values that they depend on have changed. ```svelte ``` Only values which directly appear within the `$:` block will become dependencies of the reactive statement. For example, in the code below `total` will only update when `x` changes, but not `y`. ```svelte Total: {total} ``` It is important to note that the reactive blocks are ordered via simple static analysis at compile time, and all the compiler looks at are the variables that are assigned to and used within the block itself, not in any functions called by them. This means that `yDependent` will not be updated when `x` is updated in the following example: ```svelte ``` Moving the line `$: yDependent = y` below `$: setY(x)` will cause `yDependent` to be updated when `x` is updated. If a statement consists entirely of an assignment to an undeclared variable, Svelte will inject a `let` declaration on your behalf. ```svelte ``` ### 4. Prefix stores with `$` to access their values A _store_ is an object that allows reactive access to a value via a simple _store contract_. The [`svelte/store` module](/docs/svelte-store) contains minimal store implementations which fulfil this contract. Any time you have a reference to a store, you can access its value inside a component by prefixing it with the `$` character. This causes Svelte to declare the prefixed variable, subscribe to the store at component initialization and unsubscribe when appropriate. Assignments to `$`-prefixed variables require that the variable be a writable store, and will result in a call to the store's `.set` method. Note that the store must be declared at the top level of the component — not inside an `if` block or a function, for example. Local variables (that do not represent store values) must _not_ have a `$` prefix. ```svelte ``` #### Store contract ```js store = { subscribe: (subscription: (value: any) => void) => (() => void), set?: (value: any) => void } ``` You can create your own stores without relying on [`svelte/store`](/docs/svelte-store), by implementing the _store contract_: 1. A store must contain a `.subscribe` method, which must accept as its argument a subscription function. This subscription function must be immediately and synchronously called with the store's current value upon calling `.subscribe`. All of a store's active subscription functions must later be synchronously called whenever the store's value changes. 2. The `.subscribe` method must return an unsubscribe function. Calling an unsubscribe function must stop its subscription, and its corresponding subscription function must not be called again by the store. 3. A store may _optionally_ contain a `.set` method, which must accept as its argument a new value for the store, and which synchronously calls all of the store's active subscription functions. Such a store is called a _writable store_. For interoperability with RxJS Observables, the `.subscribe` method is also allowed to return an object with an `.unsubscribe` method, rather than return the unsubscription function directly. Note however that unless `.subscribe` synchronously calls the subscription (which is not required by the Observable spec), Svelte will see the value of the store as `undefined` until it does. ## <script context="module"> A ` ``` ## <style> CSS inside a ` ``` To apply styles to a 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 then be referenced using just `my-animation-name` elsewhere in your code. ```svelte ``` There should only be 1 top-level ` ``` ## Tags A lowercase tag, like `
`, denotes a regular HTML element. A capitalised tag, such as `` or ``, indicates a _component_. ```svelte
``` ## Attributes and props 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
``` An expression might include characters that would cause syntax highlighting to fail in regular HTML, so quoting the value is permitted. The quotes do not affect how the value is parsed: ```svelte ``` When the attribute name and value match (`name={name}`), they can be replaced with `{name}`. ```svelte ``` 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 ``` _`$$props`_ references all props that are passed to a component, including ones that are not declared with `export`. It is not generally recommended, as it is difficult for Svelte to optimise. But it can be useful in rare cases – for example, when you don't know at compile time what props might be passed to a component. ```svelte ``` _`$$restProps`_ contains only the props which are _not_ declared with `export`. It can be used to pass down other unknown attributes to an element in a component. It shares the same optimisation problems as _`$$props`_, and is likewise not recommended. ```svelte ``` > The `value` attribute of an `input` element or its children `option` elements must not be set with spread attributes when using `bind:group` or `bind:checked`. Svelte needs to be able to see the element's `value` directly in the markup in these cases so that it can link it to the bound variable. > Sometimes, the attribute order matters as Svelte sets attributes sequentially in JavaScript. For example, ``, Svelte will attempt to set the value to `1` (rounding up from 0.5 as the step by default is 1), and then set the step to `0.1`. To fix this, change it to ``. > Another example is ``. Svelte will set the img `src` before making the img element `loading="lazy"`, which is probably too late. Change this to `` to make the image lazily loaded. ## Text expressions ```svelte {expression} ``` Text can also contain JavaScript expressions: > 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}
``` ## 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 ```