Skip to content

How to bind to a function from parent component into child component in svelte 5 #11341

Answered by brunnerh
baseplate-admin asked this question in Q&A
Discussion options

You must be logged in to vote

Explicitly declare the snippet inside the component:

<Hover>
	{#snippet children(handle_mouse_enter, handle_mouse_leave)}
		<a>
			<div
				onmouseenter={handle_mouse_enter}
				onmouseleave={handle_mouse_leave}
			></div></a
		>
	{/snippet}
</Hover>

In component:

<script lang="ts">
  let { children: Snippet<[..., ...]> } = $props(); // types in [] correspond to types of arguments
  // ...
</script>
{@render children(handle_mouse_enter, handle_mouse_leave)}

(For preventDefault either do it the old-fashioned way in the event handler or use a higher order function helper that wraps the handler.)

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@baseplate-admin
Comment options

Answer selected by baseplate-admin
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