0
0
Svelteframework~5 mins

Spread props in Svelte

Choose your learning style9 modes available
Introduction

Spread props let you pass many properties to a component quickly. It saves time and keeps your code clean.

You want to pass all properties from an object to a component without listing each one.
You have a set of common props shared by many components.
You want to forward all received props to a child component.
You want to keep your component calls simple and readable.
You want to dynamically pass props based on an object.
Syntax
Svelte
<Component {...props} />

The {...props} syntax spreads all key-value pairs from the props object as individual props.

You can combine spread props with other props. Later props override earlier ones.

Examples
Passes all properties from buttonProps object to the Button component.
Svelte
<Button {...buttonProps} />
Passes all inputProps but explicitly sets type to "text". The explicit type overrides any type in inputProps.
Svelte
<Input {...inputProps} type="text" />
Spreads a new object inline to pass title and content props.
Svelte
<Card {...{title: 'Hello', content: 'World'}} />
Sample Program

This example shows how to pass multiple props from an object props to a Child component using spread props. The child receives each property as a separate prop and displays them.

Svelte
<script>
  import Child from './Child.svelte';

  let props = {
    name: 'Alice',
    age: 30,
    city: 'Wonderland'
  };
</script>

<Child {...props} />

<!-- Child.svelte -->
<script>
  export let name;
  export let age;
  export let city;
</script>

<p>Name: {name}</p>
<p>Age: {age}</p>
<p>City: {city}</p>
OutputSuccess
Important Notes

Spread props make your code shorter but be careful not to pass unwanted props.

If you spread props and also set the same prop explicitly, the explicit one wins.

Use spread props to forward all props from a parent to a child component easily.

Summary

Spread props let you pass many props from an object quickly.

You can combine spread props with explicit props; explicit ones override.

They help keep your component calls clean and flexible.