0
0
Svelteframework~30 mins

Component bindings in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Component bindings
📖 Scenario: You are building a simple Svelte app where a parent component controls a child's input value using component bindings. This is like having a remote control that changes the TV channel directly.
🎯 Goal: Create a parent and child Svelte component where the parent binds a variable to the child's input value using bind:value. When the user types in the child input, the parent variable updates automatically.
📋 What You'll Learn
Create a Child.svelte component with an <input> element
In the parent component, create a variable name initialized to ""
Bind the parent's name variable to the child's input value using bind:value
Display the current value of name in the parent component below the child
💡 Why This Matters
🌍 Real World
Component bindings let you keep data in sync between parent and child components easily, like controlling a device remotely and seeing its status update instantly.
💼 Career
Understanding component bindings is key for building interactive user interfaces in Svelte, a popular modern web framework used in many web development jobs.
Progress0 / 4 steps
1
Create the Child component with an input
Create a Svelte component file named Child.svelte. Inside it, add an <input> element with a value prop that can be bound from the parent. Use export let value to accept the value prop.
Svelte
Need a hint?

Use export let value = ""; to accept the value prop. Then bind the input's value to it with bind:value={value}.

2
Create a parent variable name
In the parent component (e.g., App.svelte), create a variable called name and initialize it to an empty string "".
Svelte
Need a hint?

Declare let name = ""; at the top of your parent component script.

3
Bind the parent's name to the child's input value
In the parent component, import the Child component. Then use it with bind:value={name} to connect the parent's name variable to the child's input value.
Svelte
Need a hint?

Use import Child from './Child.svelte'; and then <Child bind:value={name} /> in the markup.

4
Display the current value of name in the parent
Below the Child component in the parent, add a paragraph that shows the text Name: followed by the current value of the name variable using curly braces.
Svelte
Need a hint?

Use <p>Name: {name}</p> to show the current value.