Framework Integration
How to use Swapy in Svelte.
Swapy is a client-side library, meaning you need to make sure the DOM is loaded and the component is mounted before creating a new Swapy instance.
In Svelte, you can use onMount
for that. And don’t forget to destroy the Swapy instance on component destroy, using onDestroy
.
<script>
import { createSwapy } from 'swapy'
import { onDestroy, onMount } from 'svelte'
let container
let swapy = null
onMount(() => {
// If container element is loaded
if (container) {
swapy = createSwapy(container)
// Your event listeners
swapy.onSwap(event => {
console.log('swap', event)
})
}
})
onDestroy(() => {
// Destroy the swapy instance on component destroy
swapy?.destroy()
})
</script>
<div bind:this={container}>
<div data-swapy-slot="a">
<div data-swapy-item="a">
<div>A</div>
</div>
</div>
<div data-swapy-slot="b">
<div data-swapy-item="b">
<div>B</div>
</div>
</div>
</div>