bolino
bolino

Reputation: 1122

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?

Upvotes: 0

Views: 544

Answers (1)

Corrl
Corrl

Reputation: 7699

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}

Upvotes: 2

Related Questions