0
0
Svelteframework~5 mins

Default prop values in Svelte

Choose your learning style9 modes available
Introduction

Default prop values let you set a fallback value for a component property. This means the component works well even if no value is given.

You want a button component to show 'Click me' if no label is provided.
You have a card component that should show a default image if none is passed.
You want to avoid errors when a parent forgets to send a prop.
You want to make your component easier to use with sensible defaults.
Syntax
Svelte
export let propName = defaultValue;

Use export let to declare a prop in Svelte.

Assign a value with = to set the default.

Examples
This sets the default name to 'Guest' if no name is passed.
Svelte
export let name = 'Guest';
The count prop defaults to zero if not provided.
Svelte
export let count = 0;
Boolean prop with default true.
Svelte
export let isActive = true;
Sample Program

This Svelte component shows a greeting message. If you don't pass greeting or name, it uses the default values.

Svelte
<script>
  export let greeting = 'Hello';
  export let name = 'Friend';
</script>

<h1>{greeting}, {name}!</h1>
OutputSuccess
Important Notes

Default props help avoid undefined values and make components more robust.

You can override defaults by passing props when using the component.

Default values can be any valid JavaScript value, including objects and arrays.

Summary

Default prop values provide fallback values for component properties.

Use export let prop = defaultValue; in Svelte.

They make components easier and safer to use.