1. Framework Integration
  2. React (Dynamic)

When Swapy is used in vanilla JavaScript, swapping happens by directly manipulating the DOM. This will not work properly in frameworks (like React) for dynamic use cases, where slots and items can be added or removed by the user.

To make this work, Swapy needs to hand DOM updates over to the framework, by setting manualSwap: true. Each framework has its own way for that. But Swapy provides a few helpers to make it easy to set up.

Enabling manualSwap

First step is enabling manualSwap from the configs object.

// On mounted
useEffect(() => {
  swapyRef.current = createSwapy(containerRef.current, {
    manualSwap: true
  })

  return () => {
    swapyRef.current?.destroy()
  }
}, [])

Updating your JSX to use SlottedItems

Instead of displaying your data directly in JSX, you need to wrap them with slottedItems (which we’ll see how to create later in this guide).

So if this is your JSX (let’s say you’re displaying an array of users):

<div ref={containerRef}>

  <div className="users">
    {users.map((user) => (
      <div className="slot" key={user.userId} data-swapy-slot={user.userId}>

        <div className="user" key={user.userId} data-swapy-item={user.userId}>
          <span>{user.name}</span>

          <button onClick={() => {
            setUsers(users.filter(u => u.userId !== user.userId))
          }}>Delete</button>
        </div>

      </div>
    ))}
  </div>

  <button onClick={() => {
    setUsers([/*New User*/])
  }}>Add User</button>

</div>

It will become:

<div ref={containerRef}>

  <div className="users">
    {slottedItems.map(({ slotId, itemId, item: user }) => ( 
      <div className="slot" key={slotId} data-swapy-slot={slotId}>

        <div className="user" key={itemId} data-swapy-item={itemId}>
          <span>{user.name}</span>

          <button onClick={() => {
            setUsers(users.filter(u => u.userId !== user.userId))
          }}>Delete</button>
        </div>

      </div>
    ))}
  </div>

  <button onClick={() => {
    setUsers([/*New User*/])
  }}>Add User</button>

</div>

Changes are:

  • Iterate over slottedItems instead of users.
  • Access the user object by destructuring slottedItems parameter.
  • Get access to new data along user: slotId and itemId.
  • Use slotId for the key and data-swapy-slot on the slot element.
  • Use itemId for the key and data-swapy-item on the item element.

Creating a state for the current slotItemMap

SlottedItems will be created based on the current slotItemMap of the Swapy instance. So let’s create a new state for slotItemMap and update it on swap events.

import { createSwapy, utils } from 'swapy'

function App() {
  const [slotItemMap, setSlotItemMap] = useState(utils.initSlotItemMap(users, 'userId'))  
  // ...
  useEffect(() => {
    swapyRef.current = createSwapy(containerRef.current, {
      manualSwap: true
    })

    swapyRef.current.onSwap((event) => { 
      setSlotItemMap(event.newSlotItemMap.asArray) 
    }) 

    return () => {
      swapyRef.current?.destroy()
    }
  }, [])
}

To initialize slotItemMap, we used Swapy’s helper function, utils.initSlotItemMap. It takes two parameters: your data array (e.g. users), and the name of the id field in your data (e.g. userId).

Creating SlottedItems

SlottedItems is a computed array based on the current slotItemMap. In React, we can create computed values using useMemo.

function App() {
  const [slotItemMap, setSlotItemMap] = useState(utils.initSlotItemMap(users, 'userId')) 
  const slottedItems = useMemo(() => utils.toSlottedItems(users, 'userId', slotItemMap), [users, slotItemMap]) 
  // ...
}

We also used a helper function for that, utils.toSlottedItems.

Updating Swapy’s instance on add and remove

We can update the Swapy’s instance using swapy.update(). But we also need to update the current slotItemMap along with that. To save you all the work, there’s a helper function for that, utils.dynamicSwapy.

You need to use it in useEffect, like this:

function App() {
  const [slotItemMap, setSlotItemMap] = useState(utils.initSlotItemMap(users, 'userId')) 
  const slottedItems = useMemo(() => utils.toSlottedItems(users, 'userId', slotItemMap), [users, slotItemMap])
  useEffect(() => utils.dynamicSwapy(swapyRef.current, users, 'userId', slotItemMap, setSlotItemMap), [users]) 
  // ...
}

Demo

1
2
3
+