Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can one loop through imported components in Svelte?

I’m new to Svelte. I want to import all components from a folder in Svelte and loop through them to display each of them.

In the main component App.Svelte I tried:

<script>
  import Component1 from "./lib/components/Component1.svelte";
  import Component2 from "./lib/components/Component2.svelte";
  import Component3 from "./lib/components/Component3.svelte";
  let components = Array(Component1, Component2, Component3);
</script>

<main>
  <div id="main-wrapper">
    {#each components as component}
      <component />
    {/each}
  </div>
</main>

<style>
</style>

…but it doesn’t work, no component is displayed. Why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To display a component there’s <svelte:component>tutorial

<script>
    import Comp1 from './Comp1.svelte'
    import Comp2 from './Comp2.svelte'
    import Comp3 from './Comp3.svelte'
    const components = [Comp1, Comp2, Comp3];
</script>

{#each components as component}
    <svelte:component this={component} />
{/each}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading