Skip to content

Sending DOM reference to parent from child #15178

Answered by brunnerh
karchung0930 asked this question in Q&A
Discussion options

You must be logged in to vote

I would just make it a regular (bindable) property. E.g.

<!-- Button.svelte -->
<script>
  let {
    element = $bindable(),
    children,
    ...rest
  } = $props();
</script>

<button bind:this={element} {...rest}>
  {@render children?.()}
</button>
<script>
	import Button from './Button.svelte';

	let element = $state();
</script>

<Button
  bind:element
  type="button"
  onclick={() => alert(element.textContent)}
>
  Hi
</Button>

Playground

The element will be available in the parent onMount, as is the case in the component itself.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by karchung0930
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants