[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
2
3
4
5
<!-- Nested.svelte -->

<script>
export let answer;
</script>
1
2
3
4
5
6
7
8
<!-- App.svelte -->

<script>
import Nested from './Nested.svelte';
</script>

<!-- The answer is 42 -->
<Nested answer={42}/>

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
2
3
4
5
6
7
8
9
10
11
12
<!-- App.svelte -->

<script>
import Nested from './Nested.svelte';
</script>

<!-- The answer is 42 -->
<Nested answer={42}/>

<!-- If we now add a second component without an answer prop, it will fall back to the default: -->
<!-- The answer is 40 -->
<Nested/>
1
2
3
4
5
6
7
8
<!--  Nested.svelte -->

<script>
// We can easily specify default values
export let answer = 40;
</script>

<p>The answer is {answer}</p>

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/

[3] API Docs • Svelte - https://svelte.dev/docs