Search code examples
javascriptstringcomponentssvelte

Is there any way how to pass component/html into string in Svelte?


What I am trying to achieve is to pass component into a string of a variable or some similar solution. I have tried {@html someVariable} but it works for me only in one way it means text from string to HTML. But I need the text from HTML to string. I've tried document.elementById() but always get return 'document is not defined'. Here is an example of what I'm trying to achieve:

App.svelte

<script>
import Component from './component.svelte';
import Description  from './description .svelte';


// How to declare component/html into variable?

let test = 'something like <Component /> but acceptable by variable'
let lala = test;

</script>

<Description {test} />  
Description.svelte

<script>
export let lala;
</script>

{#if something}
{@lala html}
{:else if something }
nope
{/if}

I think that this question Rendering Svelte components from HTML string has kind of the answer but I failed to make it functional.


Solution

  • Im not sure what you mean by "text from HTML to string", but if you want to pass a component to a child component you can pass it as a prop:

    <!-- App.svelte -->
    <script>
        import Component from './Component.svelte';
        import Description  from './Description.svelte';
    </script>
    
    <Description component={Component} />  
    

    To display a component that is defined in a variable you can use the <svelte:component> special element.

    <!-- Description.svelte -->
    <script>
        export let component;
    </script>
    
    {#if component}
        <svelte:component this={component}></svelte:component>
    {:else}
        component isn't set
    {/if}
    

    Here is a working Svelte REPL Link.

    If you want to learn more about the <svelte:component> special element check out the tutorial.