How to Pass Props in Svelte: Simple Guide with Examples
In Svelte, you pass props by adding attributes to a component tag and declaring
export let variables inside the child component. The parent sets values as attributes, and the child receives them as exported variables.Syntax
To pass props in Svelte, the parent component uses attributes on the child component tag. The child component declares export let variables to receive these props.
Example parts:
<ChildComponent propName={value} />in parent passesvaluetopropName.export let propName;in child declares the prop.
svelte
<!-- Parent.svelte --> <script> import Child from './Child.svelte'; let message = 'Hello'; </script> <Child greeting={message} /> <!-- Child.svelte --> <script> export let greeting; </script> <p>{greeting}</p>
Example
This example shows a parent passing a name prop to a child component, which displays a greeting message using that prop.
svelte
<!-- Parent.svelte --> <script> import Greeting from './Greeting.svelte'; let userName = 'Alice'; </script> <Greeting name={userName} /> <!-- Greeting.svelte --> <script> export let name; </script> <h1>Hello, {name}!</h1>
Output
Hello, Alice!
Common Pitfalls
Common mistakes when passing props in Svelte include:
- Not declaring
export letin the child component, so the prop is undefined. - Passing props without curly braces for variables, which passes a string instead of the variable value.
- Trying to mutate a prop directly inside the child, which is not allowed.
Correct usage requires export let and passing variables with curly braces.
svelte
<!-- Wrong: Child.svelte missing export --> <script> let greeting; // Not exported, so prop won't be received </script> <p>{greeting}</p> <!-- Right: Child.svelte with export --> <script> export let greeting; </script> <p>{greeting}</p>
Quick Reference
| Action | Syntax Example | Description |
|---|---|---|
| Declare prop in child | export let propName; | Makes propName available to receive from parent |
| Pass prop from parent | Sends value to child's propName | |
| Use prop in child | {propName} | Access the passed prop inside child template |
| Pass string literal | Passes fixed string text as prop | |
| Pass variable | Passes variable's value as prop |
Key Takeaways
Always declare props in child components using
export let.Pass props from parent using attributes with curly braces for variables.
Props are read-only inside child components; do not try to modify them directly.
String literals can be passed without curly braces, variables require curly braces.
Missing
export let causes props to be undefined in the child.