How to add components in Svelte

How to add components in Svelte

In our last article (here), We learn how to get started with the Svelte. In this article, we see:

  • How to add data in Svelte HTML
  • How to add Components in Svelte

In the App.svelte file under the main tag, remove all the contents of <p>

and add the following:

<h1>Hello {authorName}!</h1>

Under the main.js, and replace the App content with:

const app = new App({
  target: document.body,
  props: {
    name: 'world',
    authorName: 'Ash'

Refresh the webpage and we'll see

So, it's easy to add the data in the Svelte.  Everything in Svelte is component-based. Above, we added data in the default component. The upcoming section shows how to create the new component in Svelte.

Create Component

Create a new file FistComponent.svelte and add the following:

<p> This is my first component </p>

  p {
    text-align: center;
    padding: 1em;
    max-width: 240px;
    margin: 0 auto;

Go to the App.svelte and the following line under the script tag:

import FirstComponent from './FirstComponent.svelte';

And to render the component in the main tag add:

<FirstComponent />

That's it. You have added your first component in the Svelte.