How to Use Bind in Svelte: Simple Two-Way Binding Explained
In Svelte, you use
bind to create two-way data binding between a variable and an element or component property. This means changes in the UI update the variable automatically, and changes in the variable update the UI. For example, <input bind:value={name} /> keeps the input and the name variable in sync.Syntax
The bind directive in Svelte links a variable to an element or component property for two-way binding.
bind:value={variable}: Binds thevalueproperty of an input or element to a variable.bind:property={variable}: Binds any writable property of an element or component.- This keeps the variable and the UI element in sync automatically.
svelte
<input bind:value={name} />Example
This example shows how to bind a text input's value to a variable name. Typing in the input updates name, and changing name updates the input.
svelte
<script> let name = ''; </script> <input bind:value={name} placeholder="Type your name" /> <p>Hello, {name}!</p>
Output
An input box with placeholder 'Type your name' and below it text that updates live as you type, e.g., 'Hello, Alice!'
Common Pitfalls
Common mistakes when using bind include:
- Trying to bind to a read-only property (like
innerHTML), which won't work. - Forgetting to declare the variable with
letorvar, causing errors. - Using
bindon components without a matchingexport letproperty for two-way binding.
Always ensure the property you bind to supports two-way binding and the variable is declared.
svelte
<!-- Wrong: binding to read-only property -->
<input bind:innerHTML={text} />
<!-- Right: bind to value -->
<input bind:value={text} />Quick Reference
| Usage | Description | Example |
|---|---|---|
| Bind input value | Two-way bind input's value to a variable | |
| Bind checkbox checked | Two-way bind checkbox state | |
| Bind component prop | Bind a writable prop of a child component | |
| Bind select value | Bind selected option value |
Key Takeaways
Use
bind to connect variables and UI elements for automatic two-way updates.Only bind to writable properties and declared variables with
let.Binding works on native elements like inputs, checkboxes, selects, and on components with exported props.
Avoid binding to read-only properties like
innerHTML or textContent.Two-way binding simplifies syncing user input and app state without manual event handling.