Sanity Helper Functions
- #Tips & Tricks
- Mitchell Christ
An important rule in programming is: DRY
Don't Repeat Yourself
This starter template comes included with a number of helper functions to use in your Sanity Studio so you don't have to repeat yourself.
Structure Helpers
Customizing and organizing your Sanity Studio structure (where your content lives) is super easy. Here's a handy cheat sheet, too.
Singleton
๐ sanity/src/structure.ts
import { singleton } from './utils'
S.list()
.title('Content')
.items([
// ...
singleton(S, 'yourDocumentId').icon(...)
])
Group
๐ sanity/src/structure.ts
import { group } from './utils'
S.list()
.title('Content')
.items([
// ...
group(S, 'Group name', [
S.documentTypeListItem('logo').title('Logos'),
S.documentTypeListItem('testimonial').title('Testimonials'),
]).icon(...),
])
Preview Helpers
Customizing previews are also super easy. Here's official documentation on that.
Converting PortableText to a string
import { getBlockText } from '@sanity/src/utils'
preview: {
select: {
content: 'content' // this is a block type (a.k.a. PortableText)
},
prepare: ({ content }) => ({
title: getBlockText(content)
})
}
Item count
import { count } from '@sanity/src/utils'
preview: {
select: {
items: 'items' // this is an array type
},
prepare: ({ items }) => ({
title: count(items) // 1 item, 2 items
title: count(items, 'pikachu') // 1 pikachu, 2 pikachus
title: count(items, 'octopus', 'octopi') // 1 octopus, 2 octopi
})
}
Source Code
The source code for all helper functions can be found here.