Sortable
SortableList is a reusable component for reordering items in a vertical list. Render each item through a slot and attach dragging behavior to a separate handle button. It supports mouse, touch, keyboard controls, and nested lists.
Installation
1. Prepare your project
You need Vue 3.5+, TypeScript, and Tailwind CSS v4. The component uses useId(), which requires Vue 3.5 or later. A shadcn/StackTrace project usually already includes the required styles and the cn helper.
If your project does not have a components.json file yet, initialize shadcn-vue in the target project:
npx shadcn-vue@latest initThe examples on this page use the following aliases in components.json. Merge them into your existing configuration as appropriate for your project:
{
"aliases": {
"components": "@/Components",
"ui": "@/Components/Base",
"utils": "@/Utils"
}
}The @ alias must point to resources/js in both Vite and TypeScript. If you use a different aliases.ui value, adjust the example imports to match the directory where the CLI installs the component.
2. Add the component
Once the updated registry has been published, run:
npx shadcn-vue@latest add https://lib.adrianondik.com/r/sortable.jsonBefore publishing, you can use the generated local JSON file. Run this command from the target project if library is in a sibling directory:
npx shadcn-vue@latest add ../library/public/r/sortable.jsonThe registry item includes all five required files and declares laravel-vue-i18n, clsx, and tailwind-merge as dependencies. For manual installation, copy the entire registry/new-york/Components/Sortable directory into your UI directory and install any missing packages:
npm install laravel-vue-i18n clsx tailwind-mergeWith the aliases shown above, the resulting structure is:
resources/js/Components/Base/Sortable/
├── SortableList.vue
├── useSortableList.ts
├── sortable.ts
├── useSidebarOrder.ts
└── index.ts3. Check the helper and styles
SortableList.vue imports cn from @/Utils. If your project does not have this helper yet, create resources/js/Utils/index.ts:
import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}In a shadcn/StackTrace theme, drag feedback uses the existing ring color. In a standalone Tailwind project, you can add the following to your main CSS file:
@import 'tailwindcss';
@theme {
--color-ring: oklch(0.623 0.214 259.815);
}4. Initialize translations
The component uses laravel-vue-i18n for handle labels and screen reader announcements. If your application already uses i18nVue, add these three keys to your English catalog and translate their values in any additional language catalogs:
{
"Move :item": "Move :item",
"Drag to move, or use the up and down arrow keys.": "Drag to move, or use the up and down arrow keys.",
"Moved :item to position :position of :count.": "Moved :item to position :position of :count."
}In a standard Vue application, register the plugin before app.mount(). Here, messages is an object containing your language catalogs:
import { i18nVue } from 'laravel-vue-i18n'
app.use(i18nVue, {
lang: 'en',
fallbackLang: 'en',
resolve: (language: string) => messages[language] ?? {},
})In an Inertia application, register it on the Vue application using your project's existing bootstrap setup. SortableList itself does not require Inertia or a Laravel backend.
Basic usage
<template>
<SortableList
v-model="items"
:item-key="(item) => item.id"
:item-label="(item) => item.title"
as="ul"
item-as="li"
list-class="flex flex-col gap-2"
item-class="flex items-center gap-3 rounded-lg border p-3"
>
<template #default="{ item, handleProps, canSort }">
<button
v-if="canSort"
v-bind="handleProps"
class="rounded p-1 focus-visible:outline-2 focus-visible:outline-offset-2"
>
<span aria-hidden="true">⋮⋮</span>
</button>
<span>{{ item.title }}</span>
</template>
</SortableList>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { SortableList } from '@/Components/Base/Sortable'
const items = ref([
{ id: 'projects', title: 'Projects' },
{ id: 'testimonials', title: 'Testimonials' },
{ id: 'settings', title: 'Settings' },
])
</script>The component is ready to use after importing it. No global component registration or Sortable-specific Vue plugin is required. v-model receives a new array in the updated order when an item is dropped or moved with the keyboard.
itemKey must return a unique, stable string within each list. Use an ID; convert numeric IDs with String(item.id), for example. Array indices and translated labels are unsuitable keys.
Custom drag handles
Always bind handleProps to a button using v-bind. It includes drag event handlers, accessibility attributes, type="button", and the touch-none class required for touch dragging.
You can also bind it to a custom button component if it forwards attributes and events to an actual HTML <button>. For SidebarGroupAction, set as="button".
An item can contain a link and other buttons. Dragging starts only from the handle, so links continue to navigate normally.
Groups and nested lists
To reorder groups and their items, compose two instances. Each list has its own identifier and v-model:
<template>
<SortableList
v-model="groups"
:item-key="(group) => group.id"
:item-label="(group) => group.title"
item-as="section"
list-class="flex flex-col gap-4"
item-class="rounded-lg border p-3"
>
<template #default="{ item: group, handleProps, canSort }">
<header class="mb-3 flex items-center gap-2">
<button v-if="canSort" v-bind="handleProps">
<span aria-hidden="true">⋮⋮</span>
</button>
<h2>{{ group.title }}</h2>
</header>
<SortableList
v-model="group.items"
:item-key="(item) => item.id"
:item-label="(item) => item.title"
as="ul"
item-as="li"
list-class="flex flex-col gap-2"
item-class="flex items-center gap-2 rounded p-2"
>
<template #default="{ item, handleProps: itemHandleProps, canSort: canSortItems }">
<button v-if="canSortItems" v-bind="itemHandleProps">
<span aria-hidden="true">⋮⋮</span>
</button>
<span>{{ item.title }}</span>
</template>
</SortableList>
</template>
</SortableList>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { SortableList } from '@/Components/Base/Sortable'
const groups = ref([
{
id: 'content',
title: 'Content',
items: [
{ id: 'projects', title: 'Projects' },
{ id: 'testimonials', title: 'Testimonials' },
],
},
{
id: 'account',
title: 'Account',
items: [{ id: 'settings', title: 'Settings' }],
},
])
</script>This changes the order of groups and the order of items within their own group. Moving items between separate lists is not supported.
Saving the order to a user account
The component updates an array in memory. Persistence belongs to your application. Send stable IDs to the server, for example ['settings', 'projects', 'testimonials'].
The following example uses Inertia v3 useHttp and saves the order through a button. It requires an existing authenticated PATCH endpoint that accepts { order: string[] } and returns a successful response, such as 204:
<template>
<div>
<SortableList
v-model="items"
:item-key="(item) => item.id"
:item-label="(item) => item.title"
list-class="flex flex-col gap-2"
item-class="flex items-center gap-2 rounded border p-2"
>
<template #default="{ item, handleProps, canSort }">
<button v-if="canSort" v-bind="handleProps">
<span aria-hidden="true">⋮⋮</span>
</button>
<span>{{ item.title }}</span>
</template>
</SortableList>
<button type="button" class="mt-3 rounded border px-3 py-2" @click="saveOrder">
{{ request.processing ? 'Saving…' : 'Save order' }}
</button>
<p v-if="failed" role="alert">The order could not be saved. Please try again.</p>
<p v-else-if="request.recentlySuccessful" role="status">The order has been saved.</p>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useHttp } from '@inertiajs/vue3'
import { SortableList, orderItems } from '@/Components/Base/Sortable'
type Item = { id: string; title: string }
const props = defineProps<{
initialItems: Item[]
initialOrder: string[]
saveUrl: string
}>()
const items = ref(orderItems(props.initialItems, props.initialOrder, (item) => item.id))
const request = useHttp<{ order: string[] }>({ order: [] })
const failed = ref(false)
async function saveOrder() {
if (request.processing) return
failed.value = false
request.order = items.value.map((item) => item.id)
try {
await request.patch(props.saveUrl)
} catch {
failed.value = true
}
}
</script>Generate saveUrl from a named server route or use Ziggy. The endpoint must validate allowed IDs and duplicates, and save preferences only for the authenticated user. On subsequent page loads, return the saved IDs as initialOrder.
Use @change for automatic saving. When users reorder items rapidly, process requests sequentially or keep the latest pending state so an older response cannot overwrite a newer order.
Sidebar order and automatic saving
The Sortable directory also includes the optional useSidebarOrder composable and its types. Import everything from the same entry point:
import {
SortableList,
orderItems,
sidebarItemKey,
normalizeSidebarOrder,
useSidebarOrder,
type SidebarOrder,
type SidebarOrderItem,
} from '@/Components/Base/Sortable'The composable manages top-level groups and their immediate children. It normalizes saved IDs against the current menu, restores defaults, queues rapid changes, and restores the last confirmed order if saving fails. It depends only on Vue and the local sortable.ts helper. It has no dependency on application types, StackTrace, Inertia, routes, or a particular backend.
Provide a save callback that returns a promise. The following example uses Inertia v3 for that callback; the menu renderer uses the included SortableList directly:
<template>
<nav>
<SortableList
:model-value="groups"
:item-key="sidebarItemKey"
:item-label="(group) => group.title"
item-as="section"
list-class="flex flex-col gap-4"
item-class="rounded-lg border p-3"
@change="reorder('root', $event.map(sidebarItemKey))"
>
<template #default="{ item: group, handleProps, canSort }">
<header class="mb-3 flex items-center gap-2">
<button v-if="canSort" v-bind="handleProps">
<span aria-hidden="true">⋮⋮</span>
</button>
<h2>{{ group.title }}</h2>
</header>
<SortableList
:model-value="orderedChildren(group)"
:item-key="sidebarItemKey"
:item-label="(item) => item.title"
as="ul"
item-as="li"
list-class="flex flex-col gap-2"
item-class="flex items-center gap-2 rounded p-2"
@change="reorder(sidebarItemKey(group), $event.map(sidebarItemKey))"
>
<template #default="{ item, handleProps: itemHandleProps, canSort: canSortItems }">
<button v-if="canSortItems" v-bind="itemHandleProps">
<span aria-hidden="true">⋮⋮</span>
</button>
<span>{{ item.title }}</span>
</template>
</SortableList>
</template>
</SortableList>
<button type="button" class="mt-3 rounded border px-3 py-2" @click="reset">Reset order</button>
<p v-if="failed" role="alert">Saving failed. The last confirmed order has been restored.</p>
<p v-else role="status">{{ saving ? 'Saving…' : 'Drag to reorder' }}</p>
</nav>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useHttp } from '@inertiajs/vue3'
import {
SortableList,
orderItems,
sidebarItemKey,
useSidebarOrder,
type SidebarOrder,
type SidebarOrderItem,
} from '@/Components/Base/Sortable'
const props = defineProps<{
menu: SidebarOrderItem[]
savedOrder: SidebarOrder | null
saveUrl: string
}>()
const request = useHttp<{ order: SidebarOrder }>({ order: {} })
const { order, saving, failed, reorder, reset } = useSidebarOrder(
() => props.menu,
() => props.savedOrder,
async (next) => {
request.order = next
await request.patch(props.saveUrl)
},
)
const groups = computed(() => orderItems(props.menu, order.value.root ?? [], sidebarItemKey))
function orderedChildren(group: SidebarOrderItem) {
return orderItems(group.children ?? [], order.value[sidebarItemKey(group)] ?? [], sidebarItemKey)
}
</script>For this sidebar example, the backend receives an object of ID arrays rather than the flat array in the previous example:
{
"order": {
"root": ["content", "account"],
"content": ["projects", "testimonials"],
"account": ["settings"]
}
}root holds the group order. Each group ID holds that group's child order. Keep root reserved and provide stable string IDs for all persisted groups and children. The backend should validate the complete allowed structure and return the saved object as savedOrder on subsequent page loads.
SidebarOrderItem describes the minimum menu shape: { id?: string; title: string; children?: SidebarOrderItem[] }. Existing menu objects can keep extra fields such as links and icons. sidebarItemKey prefers a string id and falls back to title for menus without IDs; use explicit IDs whenever you persist preferences.
Composable inputs
| Argument | Type | Description |
|---|---|---|
menu | MaybeRefOrGetter<SidebarOrderItem[]> | The current menu. A getter keeps it synchronized with page props. |
saved | MaybeRefOrGetter<SidebarOrder | null> | Saved preferences, or null for the default order. |
save | (order: SidebarOrder) => Promise<unknown> | Your persistence callback. Reject the promise when saving fails. |
Returned state and methods
| Member | Description |
|---|---|
order | Reactive, normalized SidebarOrder map. Use it with orderItems to render lists. |
saving | Reactive flag that stays true while pending saves are processed. |
failed | Reactive flag indicating that a save failed. |
reorder(parent, identifiers) | Updates one list and saves the complete order map. Use 'root' for groups or a group ID for children. |
reset() | Restores and saves the menu's original order when it differs from the current order. |
Use normalizeSidebarOrder(menu, saved) when you only need the normalized map without saving state. The basic SortableList remains usable on its own; automatic sidebar persistence starts only when you call useSidebarOrder and connect its reorder method to list changes.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
modelValue | T[] | — | Required array of items, bound through v-model. |
itemKey | (item: T) => string | — | Required stable, unique item key. |
itemLabel | (item: T) => string | item key | Readable label for the handle and screen reader announcements. |
as | string | Component | 'div' | List container element or component, such as 'ul' or SidebarMenu. |
itemAs | string | Component | 'div' | Item element or component, such as 'li' or SidebarMenuItem. |
listClass | HTMLAttributes['class'] | — | Classes applied to the inner list. |
itemClass | HTMLAttributes['class'] | — | Classes applied to each item. |
The standard class attribute is applied to the outer <div>. Custom components passed to as and itemAs must forward attributes to their DOM element so the component can identify and measure items.
Slot and events
The default slot exposes:
| Value | Type | Description |
|---|---|---|
item | T | The current item. |
index | number | The current zero-based position. |
handleProps | attributes and event handlers | Bind to the handle button using v-bind. |
canSort | boolean | true when the list contains at least two items; otherwise, you can omit the handle. |
| Event | Payload | When it fires |
|---|---|---|
update:modelValue | T[] | After an actual order change; used by v-model. |
change | T[] | Alongside the model update; useful for side effects or saving. |
No event is emitted when dragging is cancelled or the item remains in its original position. Preserve the touch-none and select-none classes from handleProps when customizing the button.
Helper functions
import { moveItem, orderItems } from '@/Components/Base/Sortable'
const reordered = moveItem(['a', 'b', 'c'], 0, 2)
// ['b', 'c', 'a']
const items = [{ id: 'a' }, { id: 'b' }, { id: 'new' }]
const restored = orderItems(items, ['b', 'removed', 'a'], (item) => item.id)
// [{ id: 'b' }, { id: 'a' }, { id: 'new' }]Both functions return a new array. moveItem preserves the original order when an index is invalid. orderItems ignores saved IDs that no longer exist and appends new items in their original order.
Controls and limitations
- With a mouse or touch, drag the handle over the destination and release it. A highlight indicates the target item.
- When a handle is focused, use
ArrowUp,ArrowDown,Home, andEnd. - Pressing
Escape, cancelling a pointer interaction, or dropping outside the list cancels the change. - After a move, focus stays on the handle and the new position is announced to screen readers.
- Empty lists and lists with one item do not need a handle.
- The component is designed for vertical lists. Multi-column grids, horizontal sorting, and automatic scrolling while dragging are not implemented.
- The component can load during SSR without accessing the DOM. Measurement and pointer capture happen only during browser interaction.