Search code examples
bindingwidthsvelte

How to get width of svelte component


I want to store the width of a parent component and pass it down to its child component in <slot />:

<Parent bind:clientWidth={width}>
   <Child width={width}></Child>
</Parent>

I know that I can use bind:clientWidth on a normal html element like this:

<div bind:clientWidth={width}></div>

But for some reason this does not work with a svelte component:

<Component bind:clientWidth={width}></Component>

How can I get the parent width? Maybe there's a solution that doesn't involve declaring a separate variable to pass down to the child?


Solution

  • Components can be completely empty and contain multiple elements without a wrapper, they have no intrinsic size.

    If you have control over the implementation of the parent, you could internally get the size of some element and pass it as a slot property. Or you could add a wrapper element and use that to measure.

    Cannot think of a way to circumvent having an additional variable somewhere.