Is there a way to conditionally render fields in a document?
Yes, you can absolutely conditionally render fields in Sanity Studio using the conditional fields feature. This is exactly what you need for your image vs. file upload scenario.
Here's how you can set it up:
{
name: 'uploadType',
type: 'string',
title: 'Upload Type',
options: {
list: [
{title: 'Image', value: 'image'},
{title: 'File', value: 'file'}
]
}
},
{
name: 'imageUpload',
type: 'image',
title: 'Image',
hidden: ({parent}) => parent?.uploadType !== 'image'
},
{
name: 'fileUpload',
type: 'file',
title: 'File',
hidden: ({parent}) => parent?.uploadType !== 'file'
}The hidden property accepts a callback function that receives useful parameters like parent (the parent object), document (the entire document), and value (the current field value). When the callback returns true, the field is hidden; when it returns false, the field is shown.
In this example, the user first selects their upload type from a dropdown, and then only the relevant upload field appears. This keeps the interface clean and focused on what's actually needed.
Important note about validation: If you mark either upload field as required, be aware that hidden required fields still enforce validation. You'll need to implement conditional validation like this:
{
name: 'imageUpload',
type: 'image',
hidden: ({parent}) => parent?.uploadType !== 'image',
validation: (Rule) =>
Rule.custom((currentValue, {parent}) => {
return parent?.uploadType === 'image' && !currentValue
? 'An image is required when upload type is image.'
: true
})
}This feature has been available since Studio v2.17.0 and works great for reducing cognitive load by showing users only the fields they need!
Sanity โ Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.