Swapy
v1.0.3
  1. Framework Integration
  2. React

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 React, you can use useEffect with empty dependencies for that. And don’t forget to destroy the Swapy instance on component destroy.

If your use case involves adding or removing slots and items, please check out the React (Dynamic) guide.

React Example

import { createSwapy } from 'swapy'
import { useEffect, useRef } from 'react'

function App() {
  const swapy = useRef(null)
  const container = useRef(null)

  useEffect(() => {
    // If container element is loaded
    if (container.current) {
      swapy.current = createSwapy(container.current)

      // Your event listeners
      swapy.current.onSwap((event) => {
        console.log('swap', event);
      })
    }

    return () => {
      // Destroy the swapy instance on component destroy
      swapy.current?.destroy()
    }
  }, [])

  return (
    <div ref={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>
  )
}