Props, popular with other frameworks such as React and Vue.js, are a very efficient way to enable component communication. Props are used in Svelte as you’d expect. They are passed top-down from parent components to children and are used to specify data that the component can consume to inform what it renders in the DOM.
Let’s demonstrate how to make use of props by building a simple Card
component:
As you can see, you let Svelte know about the props that a component accepts by using the ES6 export
syntax. You can then make use of the props inside the component with simple value interpolation.
You can then make use of the component by providing the props like this:
With our current setup, if we fail to pass in a prop, Svelte will complain with a warning in the console:
With this, the warning will be: <Card> was created without expected prop 'imageUrl'
.
To fix that, we can provide a default value for any prop declared, using something like this:
And now you can use the Card
component without passing-in a description
or imageUrl
and the component will revert to the default values:
Similar to how you can spread props in JSX, Svelte allows you to spread props from an object in your code, to avoid the extra typing.
Here’s an example where spreading props is compared against typing in the props in the long form:
Note how it doesn’t matter that when we spread the props from our objects in items
an extra property (id
) is also passed-in. The Card
component doesn’t declare it’s use of id
as a prop, so it’s just ignored.
As you can see in the above example, I’m also making use of an each block for logic inside my markup. I’ll cover what Svelte makes available for logic in components in a future post, but you can also read all about it in the Svelte tutorial
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!