svelte

Generating .svelte component dynamically without using <svelte:component/>


Problem

I'm trying to generate svelte component dynamically in a .ts file. Thus, I'm not able to use <svelte:component> element as it can only be used inside .svelte files; in the HTML section. Is it possible to create some kind of svelte component renderer helper function?

Looking for solution

I'd need a logic for function of type: (component: SvelteComponent, props: any) => HTMLElement

Context

I figure rendering components like this might go around most (or maybe even every) intended coding patterns by Svelte, yet it would be a clean solution for what I'm trying to do. Specifically - I'm trying to inject content in Full calendar as it's described here.


Solution

  • The event can return a DOM node array and you can render any component to DOM nodes directly using the client-side component API, so e.g.:

    // Svelte 5
    import { mount } from 'svelte';
    // ...
    eventContent() {
      const content = document.createElement('div');
      mount(Component, { target: content, props: ... });
    
      return { domNodes: [content] }
    }
    
    // Svelte 3/4
    eventContent() {
      const content = document.createElement('div');
      new Component({ target: content, props: ... });
    
      return { domNodes: [content] }
    }