Cannot reassign or bind to snippet parameter. #12688
-
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.
Replies: 2 comments 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.
-
The only working solution that does not throw an error. Note that a function is passed that assigns a node |
Beta Was this translation helpful? Give feedback.
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