How to get the slots value in a Svelte component?

Viewed 1212

Say I created a component called Component, and I called it like this.

<Component>This text goes in the slot</Component>

Inside of the Component I can use <slot></slot> to display that text in the html. How can I reference its value in the script section? Is there a variable that it gets stored in?

2 Answers

To get the slot content you need to apply a trick.

In your Component wrap the slots into a span and bind the elements using bind:this

In Component.svelte

<script>
    let data;
    $: console.log(data?.innerHTML)
    $: console.log(data?.innerText)
</script>

<span bind:this={data}><slot></slot></span>

You can check it in this repl

I give below an example with named slots, also unnamed ->

In Slot.svelte

<script>
  let content ='lorem'
</script>


<slot name='named-slot' >
{content}
</slot>

In Parent component

<script>
 import Data from './Slot.svelte'
 let newData=' new content'
</script>

 
 <Data>  
 <svelte:fragment slot='named-slot' let:newData={content}>
  {newData} 
 </svelte:fragment>

 </Data>

And exmaple for unnamed slot ->

In Slot.svelte

<script>
      let content ='lorem'
    </script>
    
    <slot  >
    {content}
    </slot>

In Parent component

<script>
 import Data from './Slot.svelte'
 let newData=' new content'
</script>
    
 

 <Data let:newData={content}> 
  {newData}
   </Data>
Related