Hide array items conditionally based on document field in Sanity
Based on the documentation, you still can't conditionally hide individual array member types from the insert menu using the hidden property on the array of members. This has been a long-standing limitation in Sanity Studio.
The hidden property works great for hiding entire fields or fields within objects, but it doesn't currently work for conditionally showing/hiding which types appear in an array's insert menu. So your example code with hidden on the array member won't work as intended:
// This won't work to hide the type from the insert menu
of: [
{
type: 'page.jobListings',
hidden: ({document}) => document?.pageTemplate !== 'jobs', // ❌ Not supported
},
]Workarounds
While there's no perfect solution, here are some approaches to improve the editing experience:
1. Validation Instead of Hiding
You can prevent invalid array items from being saved using custom validation:
{
name: 'modules',
type: 'array',
of: [{type: 'page.jobListings'}],
validation: Rule => Rule.custom((modules, context) => {
const doc = context.document;
if (doc?.pageTemplate !== 'jobs' && modules?.some(m => m._type === 'page.jobListings')) {
return 'Job listings module is only available for job template pages';
}
return true;
})
}2. Different Schemas for Different Templates
Create separate document types for different page templates, each with only the relevant array members. This is cleaner but requires more schema definitions.
3. Custom Array Input Component
Build a custom input component that filters the available types based on your conditions. This gives you full control but requires more development work.
4. Conditional Entire Arrays
Instead of conditionally hiding array members, you could have different array fields that are conditionally shown:
{
name: 'jobModules',
type: 'array',
of: [{type: 'page.jobListings'}],
hidden: ({document}) => document?.pageTemplate !== 'jobs'
},
{
name: 'standardModules',
type: 'array',
of: [{type: 'hero'}, {type: 'content'}],
hidden: ({document}) => document?.pageTemplate === 'jobs'
}This approach is mentioned in this community answer as a potential workaround.
Unfortunately, there hasn't been an update to support this feature natively yet, so you'll need to choose one of these workarounds based on your specific needs and how much development effort you want to invest. The validation approach is probably the quickest win to prevent your clients from adding inappropriate modules, even if they still see them in the insert menu.
Show original thread16 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.