Skip to content

Sanity Helper Functions

  • #Tips & Tricks
Read time: 1 minute
Mitchell Christ
Mitchell Christ
Bill Murray holding a sign that says "Don't Repeat Yourself", a ground hog sticking his head out of the ground, film still from the movie Ground Hog day

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)
  })
}
Preview of portable text when used with the helper function
Line breaks will be rendered as arrows ("โ†ฉ๏ธŽ")

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.

Doc and Marty McFly in shocked expressions, with the title text "Repeat Yourself" in the style of the Back to the Future movie logo