How to Bind to Component Prop in Svelte: Simple Guide
In Svelte, you bind to a component prop using the
bind:propName syntax on the child component tag. This creates a two-way binding so changes in the child update the parent and vice versa.Syntax
To bind a prop in Svelte, use bind:propName on the child component tag in the parent. The propName must be declared as export let propName in the child component.
This syntax links the parent's variable to the child's prop, enabling two-way updates.
svelte
<!-- Child.svelte --> <script> export let value; </script> <input bind:value> <!-- Parent.svelte --> <script> import Child from './Child.svelte'; let parentValue = 'Hello'; </script> <Child bind:value={parentValue} />
Example
This example shows a parent component passing a variable to a child component's prop with two-way binding. Typing in the child's input updates the parent's variable instantly.
svelte
<!-- Child.svelte --> <script> export let text; </script> <input bind:value={text} placeholder="Type here" /> <!-- Parent.svelte --> <script> import Child from './Child.svelte'; let message = 'Hi there'; </script> <p>Parent message: {message}</p> <Child bind:text={message} />
Output
Parent message: Hi there
[input box with 'Hi there' editable text]
Common Pitfalls
- Not declaring the prop with
export letin the child component prevents binding. - Using one-way prop passing (
prop={value}) instead ofbind:propdoes not create two-way binding. - Binding to a prop that is not a writable variable in the parent causes errors.
svelte
<!-- Wrong: no export in child --> <script> let count; </script> <!-- Right: export let count --> <script> export let count; </script> <!-- Wrong: one-way prop --> <Child count={count} /> <!-- Right: two-way binding --> <Child bind:count={count} />
Quick Reference
Remember these key points for binding props in Svelte:
- Child props must be declared with
export let. - Use
bind:propNameon the child component tag for two-way binding. - Parent variable must be writable (not a constant).
- Binding works well with form elements inside the child.
Key Takeaways
Use
bind:propName on the child component tag to create two-way binding.Declare props in the child component with
export let propName to enable binding.The parent variable bound must be writable to reflect changes.
One-way prop passing does not allow updates from child to parent.
Binding is especially useful for syncing form inputs between components.