Introduction
Swapy is a small JavaScript library that adds drag-to-swap functionality to any HTML layout. Rather than implementing complex drag-and-drop from scratch, Swapy lets you mark slots and items with data attributes and get a working swappable grid or layout in minutes. It works with any framework or no framework at all.
What Swapy Does
- Converts static layouts into interactive drag-to-swap interfaces
- Works with any frontend framework: React, Vue, Svelte, or vanilla JS
- Handles all pointer events, animations, and collision detection internally
- Provides callbacks for swap events to sync with application state
- Supports dynamic slot and item addition and removal
Architecture Overview
Swapy identifies slots and items through HTML data attributes, then attaches pointer event listeners to manage the drag interaction. When a user drags an item over another slot, Swapy calculates the swap using bounding-box collision detection and animates the transition with CSS transforms. The library is framework-agnostic because it operates on the DOM directly.
Self-Hosting & Configuration
- Install via npm, pnpm, or yarn
- Add data-swapy-slot and data-swapy-item attributes to your HTML
- Call createSwapy() on the container element
- Customize animation duration and easing through options
- Listen for swap events to persist layout changes
Key Features
- Minimal API: two data attributes and one function call to get started
- Framework-agnostic — works with React, Vue, Svelte, and plain HTML
- Smooth CSS-based swap animations with configurable easing
- Lightweight with no dependencies
- Supports both grid and freeform layouts
Comparison with Similar Tools
- dnd-kit — React-specific; Swapy works with any framework
- SortableJS — reordering lists; Swapy focuses on slot-based swapping
- react-beautiful-dnd — React only and archived; Swapy is active and universal
- Framer Motion layout — animation library; Swapy is purpose-built for swap interactions
FAQ
Q: Does it work with React? A: Yes, Swapy works with React, Vue, Svelte, Angular, and vanilla JavaScript.
Q: Can I persist the layout after swaps? A: Yes, the onSwap callback provides the current layout data which you can save to localStorage or a database.
Q: Does it support touch devices? A: Yes, Swapy handles both mouse and touch pointer events natively.
Q: How large is the bundle? A: Swapy is lightweight with no external dependencies, keeping the bundle small.