Sanity.io finally supports "Initial Values" to Schemas

Sanity.io finally supports "Initial Values" to Schemas

ยท

2 min read

I've been waiting for this feature for literally 2 years! As of 4/23/2021 it is now part of Sanity canary release.

To get started, you should first read the up and running with sanity

After which, you'll wanna upgrade to the latest canary:

sanity upgrade --tag=canary --save-exact

Ok so, The end goal is to make two documents: "responsiveImage" and "aspectRatio". For this example, we will want to compose an "aspectRatio" document into "responsiveImage". This has always been possible but what wasn't possible is setting intitialValues from one document and those initialValues to carry over when composing into another.

Let's start with a directory and call it responsive-images

image.png

export default {
  name: 'aspectRatios',
  title: 'AspectRatios',
  type: 'document',
  fields: [
    {
      type: "string",
      name: "defaultAspectRatio",
      title: "Default Aspect Ratio",
      options: {
        list: [
          {title: '16x9', value: 'aspect-ratio-16x9'},
          {title: '4x5', value: 'aspect-ratio-4x5'}
          // ... add as many as you like
        ],
        layout: "radio",
        direction: "horizontal",
      },
      initialValue: 'aspect-ratio-4/5' // new supported initialValues
    },
  ]
}

In the end you'll get a piece of UI that looks like this:

image.png

Now let's compose this document into another. I want an image that supports an aspectRatio:

image.png

From the schema paste something like this in:

export default {
  name: 'responsiveImage',
  title: 'Responsive Image',
  type: 'document',
  fields: [
    {
      name: "aspectRatios",
      title: "Aspect Ratios",
      type: "responsiveImage",
    },
    {
      name: "image",
      title: "Default Source",
      type: "image",
    }
  ]
}

Finally import and add your schemas to the schema.js of sanity:

import ResponsiveImage from '../../components/responsive-image/schema';
import AspectRatio from '../../components/aspect-ratio/schema';

export default createSchema({
  name: 'default',
  types: schemaTypes.concat([
    AspectRatio 
    ResponsiveImage,
  ])
})

And when reviewing your new Responsive Image Schema you are presented with this:

image.png

As you can see all the initial values carry over between document!

Cheers ๐Ÿป, Matthew Harwood

S O C I A L :

๐Ÿ“ธ Rich.Engineer_

๐Ÿฆ RichEngineer_

ย