Declare and pass in properties to a Svelte 3 component

Tomasz Łakomy
InstructorTomasz Łakomy

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

One of the key advantages of having a component system is the ability to render the component differently based on what kind of properties (shortened to 'props' in Svelte) were passed in to the component.

In this lesson we are going to learn how to declare properties inside of a Svelte component and how to pass in data to be rendered inside of a <UserInfo /> component. We're also going to learn how to use default props which are used if a value for a property was not passed in.

Tomasz: [0:00] Right now, our app is displaying this user info component. If we take a look inside of this component, we're going to see that we specify name and a surname. We are displaying those over here.

[0:10] Right now, this component is not really generating because those two values are hardcoded within this component. Instead, we would like to be able to provide props. What I would like to have is name Tomasz and, for instance, surname Kowalski, like this.

[0:27] We would like to make it work. In order for that to happen, we need to go inside of this user info component. Instead of setting those values to John and Doe, we're going to remove those. Instead, we're going to export those two variables.

[0:42] We can see the result over here. This is how a Svelte component can expose its API. Basically, we export variables that we would like to be able to pass in as props from other components.

[0:53] We can also set default values to our props. If I were to set name to be John by default, go inside of this App.svelte component, and remove this name prop -- we are not going to pass in any prop for name -- after I save, we're going to see that this change has been applied.

[1:10] I am not passing a name prop, but even though I'm not passing anything, Svelte is going to use the default value for the name prop specified over here.