Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent node dimensions in svelte

Tags:

html

css

svelte

I'm trying to use Svelte and it's my first time so sorry for maybe the stupid question. I read the Svelte documentation but I'm stuck with a simple problem.

Basically, I would like to get the parent dimensions (width and height) of a component.

Example:

<div>
  <MyNode />
</div>

Inside MyNode I would like to have the dimensions of the parent div. How can I do that?

I tried this:

<script lang="ts">
  import { onMount, tick } from 'svelte'

  let w = 0
  let h = 0
  console.log({ w, h })

  onMount(async () => {
    console.log('on mount')
    console.log({ w, h })
    // await tick()
  })
</script>

<main>
  <div class="flex w-screen h-screen">
    <div class="white w-150 min-w-150 h-full">side menu</div>

    <div
      class="bg-ligthGrey flex-grow h-full border border-orange-500"
      bind:clientWidth={w}
      bind:clientHeight={h}
    >
      content
    </div>
  </div>
</main>

this is what I get:

enter image description here

This is printed only the first time (of course, it is inside the onMount), if I resize the window, nothing change. I need to have w and h always updated. How can I do?

like image 859
marielle Avatar asked Feb 11 '26 03:02

marielle


1 Answers

If you make the log reactive $: console.log({ w, h }) it will execute whenever w or h changes

To have the dimensions of the parent div inside the component I would pass them as a prop REPL

<script>
    import MyNode from './MyNode.svelte'
    
    let w, h
</script>

<div bind:clientWidth={w} bind:clientHeight={h}>
    <MyNode parentWidth={w} parentHeight={h}/>
</div>

<style>
    div {
        background: lightblue;
    }
</style>
MyNode.svelte
<script>
    export let parentWidth, parentHeight    
</script>

MyNode - parentWidth: {parentWidth} - parentHeight: {parentHeight}

(Notice that parentWidth and parentHeight will initially be undefined inside the component - depending on what you plan to do based on them, this should be handled)

like image 76
Corrl Avatar answered Feb 13 '26 16:02

Corrl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!