Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the value of a slot in a Svelte 3 component?

I've been playing around with Svelte 3. I'm trying to create a basic Link component that's used like this:

<Link to="http://google.com">Google</Link>

My component renders a normal HTML <a> tag with a favicon in front of the link text:

<script>
  export let to
  const imageURL = getFaviconFor(to)
</script>

<a href={to}>
  <img src={imageURL} alt={`${title} Icon`} />
  <slot />
</a>

The title variable I'm showing in the alt attribute for my <img> tag needs to be the text value of the unnamed slot. This is a really basic example, but is there any way to get the value of a slot like this?

like image 315
Scott Martin Avatar asked May 13 '19 01:05

Scott Martin


1 Answers

In the mean time I found another (even better and not so hacky) way:

<script>
  export let to
  let slotObj;
  const imageURL = getFaviconFor(to)
</script>

<a href={to}>
  <img src={imageURL} alt={slotObj? slotObj.textContent + ' Icon' : 'Icon'} />
  <span bind:this={slotObj}><slot/></span>
</a>
like image 80
voscausa Avatar answered Sep 21 '22 06:09

voscausa