In Svelte, we can use the <svelte:component> directive to render components dynamically. In this article, we will create a Svelte project and render dynamic components.

Project Setup

Let’s create a basic project structure using the Svelte + Vite template.

Run the below command to create the project folder.

npm create vite@latest dynamic-components-svelte-project -- --template svelte

This will create a folder dynamic-components-svelte-project in your current working directory. Feel free to change it to any name you want for your svelte project.

Next, navigate to the project folder and install all the packages required for the Svelte project by running the following command.

npm install

Once, the packages are installed, start the development server.

npm run dev

This will run our server on port 5173 by default. Open your web browser and visit http://localhost:5173/

Dynamic Components

Now that we have a project ready, let’s create and render two components dynamically.

The first component will be HomePage.svelte

// HomePage.svelte
<h2> This is Home page </h2>

Second, ContactPage.svelte

// ContactPage.svelte
<h2> This is Contact page </h2>

Let’s modify App.svelte to include both components. We will store the component in a variable and update it as needed.

By default, the component variable will be assigned HomePage component.

// App.svelte

<script>
  import HomePage from "./HomePage.svelte";
  import ContactPage from "./ContactPage.svelte";

  let component = HomePage;
</script>

We will add two buttons with an on-click event to change the components. We will also declare two functions to set the component when respective buttons are clicked.

Finally, we will add the <svelte:component> directive that will allow us to change the components.

// App.svelte

<script>
  import HomePage from "./HomePage.svelte";
  import ContactPage from "./ContactPage.svelte";

  let component = HomePage;

  const home = () => {
    component = HomePage;
  };

  const contact = () => {
    component = ContactPage;
  };
</script>

<button on:click={home}>Home</button>
<button on:click={contact}>Contact</button>

<svelte:component this={component} />

dynamic-components-svelte-1

dynamic-components-svelte-2

The home page component is loaded by default. When you click the contact button, the contact page component gets loaded. This way we can dynamically render components using <svelte:component> directive.

That’s it! 🙂