0
0
SvelteHow-ToBeginner · 3 min read

How to Bind to Textarea in Svelte: Simple Two-Way Binding

In Svelte, you bind to a textarea by using the bind:value directive on the textarea element. This creates a two-way binding so the variable updates as the user types and the textarea shows the variable's current value.
📐

Syntax

Use bind:value on a textarea to connect its content to a variable. This means the variable always matches the textarea's text, and changing the variable updates the textarea.

  • bind:value={variable}: links the textarea's text to variable.
  • The variable must be declared in the script section.
svelte
<script>
  let message = '';
</script>

<textarea bind:value={message}></textarea>
Output
A textarea box that updates the 'message' variable as you type.
💻

Example

This example shows a textarea bound to a variable message. Below the textarea, the current content of message is displayed live as you type.

svelte
<script>
  let message = 'Hello, Svelte!';
</script>

<textarea bind:value={message} rows="4" cols="40"></textarea>
<p>You typed: {message}</p>
Output
A textarea with initial text 'Hello, Svelte!' and below it the text 'You typed: Hello, Svelte!'. As you type, the text below updates live.
⚠️

Common Pitfalls

Common mistakes when binding to a textarea include:

  • Forgetting to use bind:value and instead using value attribute only, which does not update the variable.
  • Not declaring the variable in the <script> block, causing errors.
  • Trying to use two-way binding with on:input without updating the variable manually, which is more complex and unnecessary.
svelte
<script>
  let text = '';
</script>

<!-- Wrong: value attribute only, no binding -->
<textarea value={text}></textarea>

<!-- Right: use bind:value for two-way binding -->
<textarea bind:value={text}></textarea>
Output
The first textarea does not update 'text' as you type; the second textarea updates 'text' live.
📊

Quick Reference

FeatureUsageDescription
Bind textarea valuebind:value={variable}Two-way binding between textarea content and variable
Declare variablelet variable = '';Variable must be declared in script for binding
Display variable{variable}Show current value of variable in markup
Avoid value attribute onlyDo not use value={variable} aloneDoes not update variable on input

Key Takeaways

Use bind:value on textarea for simple two-way binding in Svelte.
Always declare the bound variable in the <script> block.
Avoid using the value attribute alone on textarea as it does not update the variable.
Binding updates the variable live as the user types and updates the textarea if the variable changes.
Displaying the variable in markup shows live updates reflecting the textarea content.