[Svelet Tutorial] 3. Props
3. Props
a. Declaring props
In any real application, you’ll need to pass data from one component down to its children. To do that, we need to declare properties, generally shortened to props
. In Svelte, we do that with the export
keyword. Edit the Nested.svelte component:
1 | <!-- Nested.svelte --> |
1 | <!-- App.svelte --> |
Just like $:
, this may feel a little weird at first. That’s not how export normally works in JavaScript modules! Just roll with it for now — it’ll soon become second nature.
b. Default values
1 | <!-- App.svelte --> |
1 | <!-- Nested.svelte --> |
c. Spread props
If you have an object of properties, you can ‘spread’ them onto a component instead of specifying each one:
1 | <Info {...pkg}/> |
Conversely, if you need to reference all the props that were passed into a component, including ones that weren’t declared with export, you can do so by accessing $$props
directly. It’s not generally recommended, as it’s difficult for Svelte to optimise, but it’s useful in rare cases.
1 | <Widget {...$$props}/> |
$$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.
1 | <input {...$$restProps}> |
References
[1] Props / Declaring props • Svelte Tutorial - https://svelte.dev/tutorial/declaring-props
[2] Svelte • Cybernetically enhanced web apps - https://svelte.dev/