Persistent Child Component #10765
-
Hey, I have this example set up where I have a component with some state that I'd like to persist (a counter) and a wrapper component (a border). The border applies a div around the child component, and removes it when the border is toggled on and off. Is there a way, with the new snippets stuff, to not unmount the child component, but move it in and out of the div? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To my knowledge the only way to have elements move is via...
You could render the snippet programmatically and move the contents around, it's quite hacky, though. Relevant code<script>
import { mountSnippet } from './Render.svelte';
let { children } = $props();
let border = $state(true);
let renderedChildren = null;
function insertDom(node) {
if (renderedChildren == null) {
mountSnippet(node, children);
renderedChildren = [...node.childNodes];
}
node.replaceWith(...renderedChildren);
}
</script>
<button onclick={() => border = !border}>
Toggle Border
</button>
{#snippet insert()}
<div use:insertDom />
{/snippet}
{#if border}
<div>
{@render insert()}
</div>
{:else}
{@render insert()}
{/if} <!-- Render.svelte -->
<script context="module">
import { mount } from 'svelte';
import Render from './Render.svelte';
export function mountSnippet(target, snippet, args) {
return mount(Render, { target, props: { snippet, args }});
}
</script>
<script>
const { snippet, args } = $props();
</script>
{@render snippet(args)} |
Beta Was this translation helpful? Give feedback.
To my knowledge the only way to have elements move is via...
{#each}
block (items can change position)You could render the snippet programmatically and move the contents around, it's quite hacky, though.
Making something like this work with SSR would probably require conditional branching.
Relevant code