Suppose I have a reusable component called button.svelte
,
<script>
export let text = undefined
</script>
<button>{text}</button>
Now I reuse this component in another component like so,
<script>
import { onMount } from "svelte"
import Button from "./Button.svelte"
let button
onMount(() => {
console.log(button) // How do I print the html of the button element?
})
</script>
<Button text="Button" bind:this="{button}"></Button>
But button
of bind:this
doesn't seem to have the html of the button element. How do I get the html element of the button?
Suppose I have a reusable component called button.svelte
,
<script>
export let text = undefined
</script>
<button>{text}</button>
Now I reuse this component in another component like so,
<script>
import { onMount } from "svelte"
import Button from "./Button.svelte"
let button
onMount(() => {
console.log(button) // How do I print the html of the button element?
})
</script>
<Button text="Button" bind:this="{button}"></Button>
But button
of bind:this
doesn't seem to have the html of the button element. How do I get the html element of the button?
1 Answer
Reset to default 16To achieve this you have to do 2 things
bind element to prop using
bind:this={prop}
.access the element in the parent component via the bonded prop and the important part is that you must do that in a reactive statement
$:
.
Button.svelte
<script>
export let node
</script>
<button bind:this={node}>
<slot />
</button>
import Button component
<script>
import Button from './Button.svelte'
let button
$:console.log(button)
</script>
<Button bind:node={button}>
Hello
</Button>
button.innerHTML
but showsundefined
– Axel Commented Apr 30, 2021 at 13:20