by Sai gowtham

Intro to Svelte.js Components

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.

components-live-example-demo 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.

MyfirstComponent.svelte
<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.

MysecondComponent.svelte
<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.

svelte-components-nesting

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course