Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading