5
votes

I have a component (IconInline.html), within which I would like to import and render components dynamically based on a prop (IconID) passed to it.

Currently I do it manually like this:

{{#if IconID === "A"}}
    <A />
{{elseif IconID === "B"}}
    <B />
{{elseif IconID === "C"}}
    <C />
{{elseif IconID === "D"}}
    <D />
{{/if}}

<script>
    import A from "./icons/A.html";
    import B from "./icons/B.html";
    import C from "./icons/C.html";
    import D from "./icons/D.html";

    export default {
        components: { A, B, C, D }
    };
</script>

Is there a way to

  1. Import all components in a given directory dynamically?
  2. Render a specific component that matches a given prop?
1

1 Answers

5
votes

There's no way to import all components in a given directory, but you can render components that match a specific prop using <svelte:component>:

<svelte:component this={cmp} foo="bar" baz="bop">
  <!-- contents go here -->
</svelte:component>

<script>
  import A from "./icons/A.html";
  import B from "./icons/B.html";
  import C from "./icons/C.html";
  import D from "./icons/D.html";

  const components = { A, B, C, D };

  export default {
    computed: {
      cmp: ({ IconID }) => components[IconID]
    }
  };
</script>

If IconID was "A", that would be equivalent to

<A foo="bar" baz="bop">
  <!-- contents go here -->
</A>

Docs here.