Cannot reassign or bind to snippet parameter. #12688
Answered
by
brunnerh
leandergangso
asked this question in
Q&A
-
Hey, I have a component that accepts a snippet. I want to be able to // --- Component.svelte
<script lang="ts">
interface Props {
trigger: Snippet<[{ refElem: HTMLElement }]>
}
let { trigger }: Props = $props()
let ref: HTMLElement
onMount(() => {
ref.addEventListener(...)
return () => ref.removeEventListener(...)
})
</script>
{@render trigger({ refElem: ref })}
// --- page.svelte
<Component>
{#snippet trigger({ refElem })
<button bind:this={refElem}>my btn</button>
{/snippet}
</Component/> see playground I read somewhere that we can bind to object properties, but not directly. |
Beta Was this translation helpful? Give feedback.
Answered by
brunnerh
Aug 1, 2024
Replies: 1 comment 1 reply
-
You cannot bind to destructured primitive arguments and you have to pass in a state object that you can reference, so one of its properties can be bound. E.g. <!-- Component -->
<script lang="ts">
import { onMount } from 'svelte'
interface Props {
trigger: Snippet<[{ refElem: HTMLElement }]>
}
let { trigger }: Props = $props()
let obj = $state({ ref: null });
onMount(() => {
console.log(obj.ref ? "ok" :"no")
})
</script>
{@render trigger(obj)} <!-- App.svelte -->
<script lang="ts">
import Component from './Component.svelte'
</script>
<Component>
{#snippet trigger(obj)}
<button bind:this={obj.ref}>my btn</button>
{/snippet}
</Component> |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
leandergangso
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You cannot bind to destructured primitive arguments and you have to pass in a state object that you can reference, so one of its properties can be bound. E.g.
REPL