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: Get the most out of your content

Sanity.io is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. Sanity.io comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Sanity.io. Free to get started, pay-as-you-go on all plans.