How to use props in Svelte

Learn how to use props in Svelte and make two components with parent/child relationship communicate with each other

You can import Svelte components into any other components using the following syntax:import ComponentName from 'componentPath':

<script>
import SignupForm from './SignupForm.svelte';
</script>

The path is relative to the current component path../Means "same folder". You will use../Return a folder, and so on.

When you are done, you can use the newly imported components in the markup, such as HTML tags:

<SignupForm />

In this way, you will form a parent/child relationship between two components: one is the imported component and the other is the imported component.

Usually, you want to let the parent component pass data to the child component.

you can use itProps. The behavior of props is similar to attributes in pure HTML and is a form of one-way communication.

In this example, we passeddisabledProps, pass JavaScript valuestrueRegarding this:

<SignupForm disabled={true}/>

In the SignupForm component, you needExitThisdisabledProps, in this way:

<script>
  export let disabled
</script>

This is how you express the fact that the props are exposed to the parent widget.

When using a component, you can pass a variable instead of a value to change it dynamically:

<script>
import SignupForm from './SignupForm.svelte';
let disabled = true
</script>

<SignupForm disabled={disabled}/>

when. . . whendisabledAfter the variable value is changed, the sub-component will be updated with the new prop value. example:

<script>
import SignupForm from './SignupForm.svelte';
let disabled = true
setTimeout(() => { disabled = false }, 2000)
</script>

<SignupForm disabled={disabled}/>

Download mine for freeSlim Handbook


More subtle tutorials: