0
0
SvelteHow-ToBeginner · 3 min read

How to Set Default Prop Value in Svelte Components

In Svelte, you set a default prop value by assigning it directly in the export let statement, like export let name = 'Guest';. This way, if the parent component does not provide a value, the default is used automatically.
📐

Syntax

To set a default prop value in Svelte, you use the export let syntax with an assignment. This means you declare the prop and assign it a default value in one line.

  • export let propName = defaultValue; declares a prop named propName with a default value defaultValue.
  • If the parent component does not pass a value, Svelte uses the default.
  • If the parent passes a value, it overrides the default.
svelte
export let propName = defaultValue;
💻

Example

This example shows a Svelte component that has a prop name with a default value of 'Guest'. When used without passing name, it shows the default. When name is passed, it shows the passed value.

svelte
<script>
  export let name = 'Guest';
</script>

<h1>Hello, {name}!</h1>
Output
Hello, Guest!
⚠️

Common Pitfalls

One common mistake is to declare the prop without a default and then try to set the default inside the component logic, which is unnecessary and can cause confusion.

Wrong way:

<script>
  export let name;
  if (!name) {
    name = 'Guest';
  }
</script>

Right way:

<script>
  export let name = 'Guest';
</script>

Also, avoid using undefined or null as default values if you want a meaningful fallback.

📊

Quick Reference

  • Use export let prop = defaultValue; to set defaults.
  • Defaults apply only if parent does not pass a value.
  • Props are reactive and update if parent changes them.
  • Do not set defaults inside <script> logic after declaration.

Key Takeaways

Set default prop values by assigning them in the export statement like export let prop = defaultValue;.
Default values are used only when the parent component does not provide a prop value.
Avoid setting default values inside component logic after declaring the prop.
Props in Svelte are reactive and update automatically when changed by the parent.
Use meaningful default values to ensure your component behaves predictably.