Intro to Svelte.js Components
In this tutorial, we are going to learn about how to create components in svelte.
Components
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 html,css and javascript
.
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 component called MyfirstComponent.svelte
where it contains
html,css and javascript
.
script: In the script tag, we need to write javascript related code.
style: In style tag, we need to write CSS code (the styles are scoped).
The { }
brace is used to interpolate the javascript data into the markup.
Note: The data present inside the
script
can only be accessible inside the component.
Nested components
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.