How to manage order of displayed items in Sanity Structure Builder?
You can definitely manage the order of displayed items in the Structure Builder, and yes, you can preserve the order of references! Let me break down the different aspects of ordering:
Ordering List Items with defaultOrdering
For document lists, you can use the defaultOrdering method to control the sort order:
S.documentList()
.title('Posts')
.filter('_type == "post"')
.defaultOrdering([
{field: 'publishedAt', direction: 'desc'},
{field: 'title', direction: 'asc'}
])Important gotcha: If you've previously selected a custom sort order in the Studio, it will be saved in local storage and override your defaultOrdering configuration. Clear your browser's local storage if your configuration doesn't seem to work.
Preserving Order of References in GROQ
When you dereference an array of references in GROQ (like tags[]->, the order is automatically preserved. GROQ maintains the array order when dereferencing, so if your document has references in a specific order, they'll appear in that same order when you query them.
For example:
S.documentList()
.title('Items with their tags')
.filter('_type == "item"')
.child(itemId =>
S.documentList()
.title('Tags for this item')
.filter('_id in *[_type == "item" && _id == $itemId][0].tags[]._ref')
.params({itemId})
)The tags will appear in the order they're stored in the tags array on your item document.
Using child with Custom Ordering
If you need more control over how references are displayed while preserving their order, you can use the child method with a custom resolver and getClient from the context:
export const structure = (S, context) =>
S.list()
.title('Content')
.items([
S.listItem()
.title('Items')
.child(
S.documentList()
.title('All Items')
.filter('_type == "item"')
.child(async (itemId) => {
// Fetch the item to get its tags in order
const client = context.getClient({apiVersion: '2024-01-01'})
const item = await client.fetch(
'*[_type == "item" && _id == $itemId][0]{ tags[]-> }',
{itemId}
)
return S.list()
.title('Tags (in order)')
.items(
item.tags.map(tag =>
S.documentListItem()
.id(tag._id)
.schemaType('tag')
)
)
})
)
])The key insight is that GROQ's tags[]-> syntax preserves the array order, so you don't need special functions to maintain the reference order—it's built into how GROQ works. When you dereference an array of references, they maintain their original position in the array, which is exactly what you need for keeping the order of tags or other referenced documents.
Show original thread6 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.