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 >
<div >side menu</div>
<div
bind:clientWidth={w}
bind:clientHeight={h}
>
content
</div>
</div>
</main>
this is what I get:
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?
CodePudding user response:
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)
CodePudding user response:
Unlike in other frameworks the code between script
tags is only executed once, during initialization. This explains why you see the {w: 0, h: 0 }
as those are values at that time.
To indicate that a piece of code should run again, you have to explicetely mark it as 'reactive'. In your case this would be:
$: console.log({w, h});
You can do the tutorial to learn more about this: https://svelte.dev/tutorial/reactive-assignments