In this tutorial, we are going to learn about how to create components in svelte.
Components are the reusable piece of UI where we can create once and reuse throught in our app.
In svelte we can create components by creating a file with
.svelte extension each svelte component consists of
Let’s write our first svelte component.
<script> let name = "component" </script> <style> h1 color:red; </style> <h1>My first name</h1>
In the above code we have created our called component
MyfirstComponent.svelte where it contains
style: In style tag, we need to write CSS code (the styles are scoped).
Note: The data present inside the
scriptcan only be accessible inside the component.
It is hard to build an entire app inside a single component so that we can import and use one component inside other components. Let’s see an example.
<script> import MyfirstComponent from './MyfirstComponent.svelte'</script> <style> </style> <div> <h1>My second component</h1> <MyfirstComponent/></div>
In script we have imported the
MyfirstComponent and added it to the markup just like html element.