How to work with props in Svelte
Learn how to work with props in Svelte and let two components with a parent/child relationship communicate with each other
You can import a Svelte component into any other component using the syntax import ComponentName from 'componentPath':
<script>
import SignupForm from './SignupForm.svelte';
</script>
The path is relative to the current component path.
./means “this same folder”. You’d use../to go back one folder, and so on.
Once you do so, you can use the newly imported component in the markup, like an HTML tag:
<SignupForm />
In this way, you are forming a parent/child relationship between the two components: the one that imports, and the one that is imported.
Often you want to have the parent component pass data to the child component.
You can do so using props. Props behave similarly to attributes in plain HTML, and they are a one-way form of communication.
In this example we pass the disabled prop, passing the JavaScript value true to it:
<SignupForm disabled={true}/>
In the SignupForm component, you need to export the disabled prop, in this way:
<script>
export let disabled
</script>
This is the way you express the fact that the prop is exposed to parent components.
When using the 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 the disabled variable value changes, the child 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 all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.