Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import and render components dynamically in Svelte/Sapper?

Tags:

svelte

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?
like image 540
Jonas K. Avatar asked Apr 30 '18 14:04

Jonas K.


1 Answers

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.

like image 160
Rich Harris Avatar answered Jan 01 '23 08:01

Rich Harris