Show/Hide Field Based on Boolean in Sanity - How Does It Work?
Great question! Your code is working perfectly, and you've actually discovered one of Sanity's most useful features - Conditional Fields. Let me break down exactly how it works:
How Your Code Works
{
name: "flag",
title: "Show or Hide",
type: "boolean",
},
{
name: "entry",
type: "string",
title: "Entry",
hidden: ({document}) => !document.flag
}The hidden property accepts a callback function that determines whether the field should be hidden. This function:
- Receives a parameter object with
{document}- this gives you access to the entire document being edited - Returns a boolean -
truemeans hide the field,falsemeans show it - Evaluates
!document.flag- the!(not operator) flips the boolean value:- When
flagistrue→!document.flagisfalse→ field is shown - When
flagisfalse→!document.flagistrue→ field is hidden
- When
So your "entry" field appears when the checkbox is checked, and disappears when unchecked!
Other Useful Patterns
The callback function gives you access to several parameters you can use:
hidden: ({parent, document, value, currentUser}) => {
// parent - the parent object (useful in nested fields)
// document - the entire document
// value - the current field's value
// currentUser - info about who's editing
}Example with multiple conditions:
{
name: "specialContent",
type: "text",
hidden: ({document}) => document.contentType !== 'premium' || !document.isPublished
}Example using parent (for fields inside objects):
{
name: 'videoUrl',
type: 'url',
hidden: ({parent}) => parent?.mediaType !== 'video'
}Pro Tip: Conditional Validation
If you ever need a field to be required only when visible, combine conditional fields with conditional validation:
{
name: "entry",
type: "string",
hidden: ({document}) => !document.flag,
validation: (Rule) => Rule.custom((value, context) => {
if (context.document?.flag && !value) {
return 'Entry is required when flag is checked'
}
return true
})
}Your solution is actually the recommended approach - clean, simple, and exactly how Sanity intended conditional fields to work. Welcome to Sanity, and happy building! 🎉
Show original thread11 replies
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.