How to Use export let in Svelte: Simple Props Explanation
In Svelte, use
export let to declare a prop that a component can receive from its parent. This makes the variable reactive and accessible outside the component, allowing you to pass data into it.Syntax
Use export let variableName inside a Svelte component to declare a prop. This means the component expects a value for variableName from its parent.
- export: makes the variable accessible outside the component
- let: declares a reactive variable
- variableName: the name of the prop
svelte
export let name;
Example
This example shows a Greeting component that uses export let to accept a name prop. The parent component passes a value to name, which the child displays.
svelte
<!-- Greeting.svelte --> <script> export let name; </script> <p>Hello, {name}!</p> <!-- App.svelte --> <script> import Greeting from './Greeting.svelte'; </script> <Greeting name="Alice" />
Output
Hello, Alice!
Common Pitfalls
Common mistakes include:
- Not using
exportbeforelet, so the variable is not a prop. - Trying to assign a value to the prop inside the child component, which is read-only from the parent's perspective.
- Forgetting to pass the prop from the parent, resulting in
undefinedvalues.
svelte
/* Wrong: missing export, so 'name' is not a prop */ <script> let name = 'Bob'; </script> <p>Hello, {name}!</p> /* Right: export let makes 'name' a prop */ <script> export let name; </script> <p>Hello, {name}!</p>
Quick Reference
| Usage | Description |
|---|---|
| export let propName; | Declare a prop named propName |
| Pass value to propName from parent | |
| propName is reactive | Updates if parent changes the value |
| Do not assign to propName inside child | Props are read-only from child perspective |
Key Takeaways
Use export let to declare props that accept values from parent components.
Props declared with export let are reactive and update when parent data changes.
Always pass required props from the parent to avoid undefined values.
Do not assign new values to props inside the child component; treat them as read-only.
export let makes variables accessible and reactive for component communication.