svelte-reparent

svelte's missing reparenting utility | alternative to react-reparent.

GitHub | npm

Demo

Container A

Container B

Explanation

svelte-reparent uses a limbo to store the component to be moved around, and different portals that the component can move to.

limbo is an invisible component, and any thing inside of it will be hidden. portals are the visible components that the component can move to.

When portals are destroyed, they will move the component back to limbo. When limbo is destroyed, it will completely destroy the component, no matter where it is.

A component has portal ID metadata attatched to it, allowing the component to be owned by portals, creating a safe way to move components around.

As mentioned in the example, the input has an "unkept state". This is state that isn't stored by svelte, demonstrating that the original element is only moved, not re-rendered.

Example Code

1
<script lang="ts">
2
	import { onMount } from 'svelte';
3
	import { Portal, Limbo, teleport } from 'svelte-reparent';
4

5
	let component: HTMLElement;
6

7
	function send(label: string) {
8
		return () => teleport(component, label);
9
	}
10

11
	onMount(send('a'));
12
</script>
13

14
<main>
15
	<Limbo bind:component>
16
		<input placeholder="Enter unkept state" />
17
	</Limbo>
18
	<div class="container">
19
		<h1>Container A</h1>
20
		<Portal key="a" {component} />
21
		<button on:click={send('a')}>Move Component Here</button>
22
	</div>
23
	<div class="container">
24
		<h1>Container B</h1>
25
		<Portal key="b" {component} />
26
		<button on:click={send('b')}>Move Component Here</button>
27
	</div>
28
</main>

made with ❤️ by leo