Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

How to add options to a custom type in Sanity.io and access them in the definition.

3 replies
Last updated: Jan 3, 2022
If I'm creating a new custom type - like
localeBlock
- how can I add options to this type, and then access them inside of my definition?
Code in thread.
Jan 3, 2022, 11:24 AM
I want to create a new custom type for portable text, which supports localization. Right now, it looks like this:

export const localeBlock = {
  title: "Localized content",
  name: "localeBlock",
  type: "object",
  fields: supportedLanguages.map((language) => ({
    name: language.id,
    title: language.name,
    type: "array",
    of: [{ type: "block" }, { type: "customType" }],
  })),
};
Now, whenever I want localized block content, I can simply specify
{ type: "localeBlock" }
in my schemas:

{
  type: "document",
  name: "product",
  title: "Product",
  fields: [
    { name: 'description', type: 'localeBlock' }
  ],
}
Now, I want to be able to specify what types of custom block content I want to have in this
description
field. Perhaps I want images, perhaps I want a custom section or whatever. So I want to specify what's in the
of
array of the
localeBlock
content type, by specifying it like so:

{
  type: "document",
  name: "product",
  title: "Product",
  fields: [
    { name: 'description', type: 'localeBlock', of: [{ type: 'image' }, { type: 'customSection' }] }
  ]
}
But how can I specify that the content of the
of
section should be put into the
of
block in the first code example above? Is this even possible?
Jan 3, 2022, 11:24 AM
Ah, turns out this can be solved by using plain ol' JavaScript!
Instead of specifying a custom type, I created a function that inlines the type for me.


{
  type: "document",
  name: "product",
  title: "Product",
  fields: [
    createLocaleBlock({ 
      name: 'description', 
      of: [
        { type: 'block' }, 
        { type: 'image' }, 
        { type: 'customSection' }
      ]
    }
  ]
}
Jan 3, 2022, 11:45 AM
And the function itself looks like this:

export const createLocaleBlock = ({
  of,
  name,
  title,
  description,
  validation,
}) => ({
  title,
  name,
  description,
  type: "object",
  fields: supportedLanguages.map((language) => ({
    name: language.id,
    title: language.name,
    type: "array",
    of,
  })),
  validation,
});
Jan 3, 2022, 11:46 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?