Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an Element bind from a svelte component

I need the bounding client rect of an anchor element.

I mark that using bind:this={someVariable}

But when I add that code to a svelte component, I get some other object svelte uses to represent a component.

can I access the enclosed element or something like that from that binding? Or do I have to wrap every component with a sacrificial <div /> and bind that?

like image 209
Gal Avatar asked Oct 25 '25 02:10

Gal


1 Answers

Using bind:this does not give you a DOM Element because Svelte does not require that your component has a root element. This is a valid Svelte element:

<script>
 ...
</script>
<div>...</div>
<div>...</div>

And so is a component that does not have any markup at all:

<script>
 ...
</script>

In both those cases, it would be impossible to return a bounding client rect for these components because there is no 'root' element.

That said, what you can do is add a bind:this in your component and export that one:

<script>
  export let anchor
</script>

<svelte:options accessors></svelte:options>
<a bind:this={anchor}>...</a>

And in your parent you can now get the anchor element using child.anchor (note that by default the props are not accessible this way, that's why you need the svelte:options)

One of the reason this is not so straightforward though is that it is a very 'unsvelte' way of working, you would normally not direcly interact with the markup generated by another component (that is the domain of that component).

Alternatives could be

  • expose the client rectangle directly instead of the element
  • move what you are trying to do to the anchor component itself
like image 166
Stephane Vanraes Avatar answered Oct 27 '25 15:10

Stephane Vanraes