I am trying to create a wrapper component just to create a card with gray background. Lets call it GrayCard

GrayCard.svelte

  <script>
   
  </script>
  
  <div class="graycard-container">
      <slot />
  </div>
  
  <style>
    .graycard-container {
      background-color: #f0f0f0;
      padding: 16px;
    } 
  </style> 

But this a dynamic component, that I will get it from a different module. So I have to programmatically instantiate this component to use it.

So i create another wrapper just to make use of any such dynamic components.

DynamicComponent.svelte

<script>
import { onMount} from 'svelte';
export let props;

let remoteComponent;
let remoteComponentInstance;

onMount(async () => {     
    remoteComponent = (await import(`remoteComponent/GrayCard`));
    remoteComponentInstance = new remoteComponent.default({
        target: document.getElementById('dynamicComponent'),
        props: {
            ...props
        },

    });
});

</script>

<div id="dynamicComponent"></div>
<slot />

<style>

</style>

Since I want to use it very generically, as a wrapper in my App.svelte, I want to use it as tag only, like

In App.svelte

  <script>
      import DynamicComponent from "./lib/components/DynamicComponent.svelte";

  </script>
  
  <DynamicComponent>
      <p> Hey i am present inside a dynamic gray card</p>
  </DynamicComponent>
  
  <style>
    
  </style> 

I am able to successfully instantiate the gray card in my screen, but the contents (the children under DynamicComponent) are not coming within the graycard. I don't understand how to achieve this. Can anyone help me with this. Thank you.

PS: I am just thinking what is the right way to access the children of tag in the DynamicComponent.svelte programmatically, and place them all in the slot.

1

There are 1 best solutions below

0
Stephane Vanraes On

You should use svelte:component for this instead

<script>
  import { onMount} from 'svelte';

  export let props;
  
  let remoteComponent;
  
  onMount(async () => {     
      remoteComponent = (await import(`./GrayCard.svelte`)).default;

  });
</script>
  
{#if remoteComponent}
  <svelte:component this={remoteComponent} {...props}><slot /></svelte:component>
{/if}

The #if block is because initially remoteComponent will be empty.