How to bind to a function from parent component into child component in svelte 5 #11341
-
Hi i have a svelte 4 component that looks like this <!-- Hover.svelte -->
<script lang="ts">
import { cn } from '$functions/classnames';
let hover_glider_element: HTMLElement | null = null,
glider_container_element: HTMLElement | null = null;
const handle_mouse_enter = (event: Event) => {},
handle_mouse_leave = () => {};
</script>
<div>
<div ></div>
<slot {handle_mouse_enter} {handle_mouse_leave} />
</div>
I invoke it like this <Hover let:handle_mouse_enter let:handle_mouse_leave>
<a>
<div
on:mouseenter|preventDefault={handle_mouse_enter}
on:mouseleave|preventDefault={handle_mouse_leave}
></div></a
>
</Hover> How to implement this in svelte 5 snippets? I have managed to transform <script lang="ts">
import { cn } from '$functions/classnames';
import type { Snippet } from 'svelte';
let hover_glider_element: HTMLElement | null = null,
glider_container_element: HTMLElement | null = null;
let {
glider_container_class = null,
active_element_class = null,
direction,
GLIDER_TRANSITION_DURATION = 200,
children
}: {
glider_container_class: string | null;
active_element_class: string | null;
direction: 'horizontal' | 'vertical';
GLIDER_TRANSITION_DURATION: number;
children: Snippet<[any]>;
} = $props();
let mouse_leave_timeout: NodeJS.Timeout,
is_hovered_from_prev_el = $state(false);
const handle_mouse_enter = (event: Event) => {
},
handle_mouse_leave = () => {
};
</script>
<div bind:this={glider_container_element} class={glider_container_class}>
<div
bind:this={hover_glider_element}
class={cn(active_element_class, 'absolute opacity-0 duration-200 ease-in-out')}
></div>
{@render children()}
</div>
But i cant seem to pass the function like i did in props |
Beta Was this translation helpful? Give feedback.
Answered by
brunnerh
Apr 26, 2024
Replies: 1 comment 1 reply
-
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 |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
baseplate-admin
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explicitly declare the snippet inside the component:
In component:
(For
preventDefault
either do it the old-fashioned way in the event handler or use a higher order function helper that wraps the handler.)