concept bind in category svelte

appears as: bind, bind
Svelte and Sapper in Action

This is an excerpt from Manning's book Svelte and Sapper in Action.

This works, but it’s a bit verbose. We can do better using the Svelte bind directive. You will see many uses of the bind directive later, but one use is to bind the value of a form element to a variable. This causes the form element to display the current value of the variable. If a user changes the value of the form element, the variable will be updated to match.

  • Props pass data from parent components to child components, and optionally back to the parent using bind.
  • Slots pass content from parent components to child components so children can decide whether and where to render it.
  • The value of the form elements input, textarea, and select can be bound to a variable using the bind directive. When a form element uses this, it renders the value of the variable. If a user changes the form element’s value, the bound variable is updated to match. This simulates two-way data binding and is much easier than explicitly listening for a specific event, extracting the new value from the event, and explicitly updating a variable.

    The Svelte compiler generates the necessary event-handling code to keep the form element and variable in sync. For input elements with the type number or range, using the bind directive automatically coerces values from strings to numbers.

    The following HTML form, implemented in a single Svelte component, uses the bind directive with a variety of form element types. The result is shown in figure 5.3.\

    Figure 5.3 App demonstrating the use of bind

    Listing 5.9 App demonstrating the use of bind

    If the name of the variable in the parent component matches the name of the prop, the bind expression can be shortened. For example, these are equivalent:

    <Child bind:cValue={cValue} />
    <Child bind:cValue />

    Child components can also use reactive declarations to modify the value of a prop. If the parent component uses bind with that prop, it will also be updated.