Watch a live product demo 👀 See how Sanity powers richer commerce experiences

Conditionally show a field based off of a value inside of a reference

By RD Pennell

Use the renderDefault method to show or hide fields.

schema.js

import { ConditionalComponent } from './path/to/component'
 
//...

{
  name: 'reference',
  type: 'reference',
  to: [{ type: 'referenceDocument' }],
},
{
  name: 'sibling',
  type: 'string',
  components: {
    field: ConditionalComponent,
  },
},

ConditionalComponent.jsx

import { useEffect, useState } from 'react';
import { useClient, useFormValue } from 'sanity';

const ConditionalComponent = props => {
  const [hideSibling, setHideSibling] = useState(false);
  const { renderDefault } = props;
  const client = useClient({ apiVersion: '2023-04-01' });
  const reference = useFormValue(['reference'])._ref;

  useEffect(() => {
    if (!reference) return;
    client
      .fetch(`*[_id == $reference].hideSibling`, { reference })
      .then(setHideSibling);
  }, [client, reference]);

  return hideSibling ? null : renderDefault(props);
};

The hidden callback can't handle promises, so you'll need to use a custom component to access the Studio client. Thankfully, the renderDefault method that's passed into your component's props makes this doable in a few lines of code.

Contributor

Other schemas by author