$ git show reorder-list
Drag to reorder list
Long-press a row to lift it, drag it up or down, and the other rows slide out of its way.
⋮⋮Groceries
⋮⋮Laundry
⋮⋮Gym
⋮⋮Read
// Gesture-driven, so Reanimated 4 keeps the same worklets: one shared map of row slots
const ROW = 56;
const positions = useSharedValue<Record<string, number>>(
Object.fromEntries(items.map((item, i) => [item.id, i])),
);
function Row({ id, positions, count, children }) {
const lifted = useSharedValue(false);
const top = useSharedValue(positions.value[id] * ROW);
const startTop = useSharedValue(0);
// Slide into place whenever another row takes this one's slot
useAnimatedReaction(
() => positions.value[id],
(slot, prev) => {
if (slot !== prev && !lifted.value) {
top.value = withSpring(slot * ROW, { damping: 20, stiffness: 250 });
}
},
);
const pan = Gesture.Pan()
.activateAfterLongPress(250)
.onStart(() => {
lifted.value = true;
startTop.value = top.value;
})
.onUpdate((e) => {
top.value = startTop.value + e.translationY;
const to = Math.min(Math.max(Math.round(top.value / ROW), 0), count - 1);
const from = positions.value[id];
if (to !== from) {
// Swap with whichever row is sitting in the target slot
const next = { ...positions.value };
for (const key in next) {
if (next[key] === to) next[key] = from;
}
next[id] = to;
positions.value = next;
}
})
.onFinalize(() => {
lifted.value = false;
top.value = withSpring(positions.value[id] * ROW);
});
const style = useAnimatedStyle(() => ({
top: top.value,
zIndex: lifted.value ? 10 : 0,
shadowOpacity: withTiming(lifted.value ? 0.2 : 0),
transform: [{ scale: withSpring(lifted.value ? 1.03 : 1) }],
}));
return (
<GestureDetector gesture={pan}>
<Animated.View style={[styles.row, { position: 'absolute', left: 0, right: 0, height: ROW }, style]}>
{children}
</Animated.View>
</GestureDetector>
);
}
// Container height = items.length * ROW. Read positions.value on drop to save the new order.
<View style={{ height: items.length * ROW }}>
{items.map((item) => (
<Row key={item.id} id={item.id} positions={positions} count={items.length}>
<Text>{item.title}</Text>
</Row>
))}
</View>