Is there a way to conditionally render fields in a document?

3 replies
Last updated: Sep 25, 2020
Hey everyone. In the studio, I want the user to choose between uploading an image, or a file. Is there a way to conditionally render fields in a document?
Sep 24, 2020, 8:12 AM
Hi Erlend ๐Ÿ‘‹ Conditional fields will be easier in the future, but you can already set this up using a custom input component. This snippet lets you use a boolean type field as a condition for another field or object to show: https://github.com/sanity-io/sanity-recipes/blob/39d2fb0d079fec3a60dc1f13d6abbf6f4e3ae037/snippets/conditionalFieldsCustomInputComponent.js
There are variations of the above in case you need something more flexible, so just let me know if this isnโ€™t enough for your use case
๐Ÿ™‚
Sep 24, 2020, 11:32 AM
Thank you! ๐Ÿ™‚
Sep 24, 2020, 11:33 AM
Curious if there's a way to acheive this without the need to create a custom component. Something along the lines of:

export default {
  name: "page",
  title: "Page",
  type: "document",
  fields: [
    {
      name: "mood",
      type: "string",
      description: "How do you feel?",
      options: {
        list: [
          { title: "Good", value: "good" },
          { title: "Bad", value: "bad" },
        ],
      },
    },
    {
      name: "details",
      type: "string",
      description: "Why?",
      options: {
        condition: mood === 'bad',
      },
    },
  ],
};

Sep 25, 2020, 5:48 PM

Sanity.io โ€“ build remarkable experiences at scale

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