Create a new Svelte 3 component to render it inside of another component

Tomasz Łakomy
InstructorTomasz Łakomy

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

It's highly unlikely that we'd like to have an entire app in a single file. Instead, what we'd like to do is to spread our code across multiple components and render them in one another.

In this lesson we are going to learn how to create a <Surname /> Svelte 3 component which we're going to use in our main App.svelte file to display a user's surname.

Tomasz: [0:00] We probably don't want to have an entire app inside of a single file. Let's create a new component that we're going to use to display our surname. Over here, I'm going to create a new file. I'm going to call it surname.svelte.

[0:15] Over here, I'm going to have a script tag. I'm going to create a variable for surname, Doe. We're going to render this surname inside of an <h1> tag. MySurname is surname.

[0:28] This text is not visible because we need to render this component. After we go back to our app Svelte component, we're going to remove the surname from here. We're going to import surname from surname.svelte.

[0:45] Now we need to render this component, so we're going to use it like this. We can see the text over here. Bear in mind that even though over here I'm styling the <h1> to be of this blue color, it's not applied to the surname component because the surname component does not have those styles over here.

[1:02] If I were to add a style tag and I would set the <h1> styles to be of color red, this change would be applied only for the surname component, not to this app component which currently is displaying our name.