Getting started
Install @lukez/svelte-dnd and make a list draggable.
@lukez/svelte-dnd is a drag and drop library for Svelte 5. You write a list with an #each block, put one attachment on its container, and the user can sort it with the pointer, a touch screen or the keyboard.
Install
The peer range is svelte ^5.32.0, because the library uses attachments. It has no other dependencies.
A first list
Four things make this work:
dndzoneis an attachment. It turns the<section>into a zone and each of its direct children into a draggable item. It takes a function that returns the options, so it reads your currentitemseach time they change.- Every item has an
id, and the#eachblock uses it as its key. Keyed blocks are required. onconsiderandonfinalizeget the event directly.e.itemsis the list the zone should render, ande.infosays what happened.flipDurationMsis given to the options and toanimate:flip, so the library and the animation agree on how long a move takes.
See Options for every option the getter can return.
Why you write items back twice
The library never changes your list. It tells you what the list should look like, and you assign it:
onconsiderruns again and again while the user drags: the item has entered the zone, moved over another index, or left. Theitemsit gives you include a temporary placeholder, so the other items make room. Render that list to show the user where the item would land.onfinalizeruns when the item is dropped, in the zone the item was dropped into and in the zone it came from. Theitemsit gives you are the final list. A pointer drag sends it once, at the end. A keyboard drag sends it on every arrow key and ends with anonconsider, so read saving after a drag before you save to a server from it.
Both handlers usually do the same thing, items = e.items, so the sample above shares one function. They are two options because they mean different things: a drag in progress and a result. The library relies on both to keep your list in step with the drag, so do not leave either one out. How it works explains the full lifecycle.
Next steps
- How it works: the consider and finalize lifecycle, the placeholder item, zone types and item ids.
- Options: every option of a zone.
- The guides: drag handles, nested zones, keyboard and screen readers, styling and more.