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.