πŸ‘€ Our most exciting product launch yet πŸš€ Join us May 8th for Sanity Connect

Sanity Custom Preview Component to get Parent Document

By Surjith S M

Sanity preview component cannot access the parent/document if its inside an array or object. Using Custom Preview component, we can solve the issue.

Warning

This schema is for an older version of Sanity Studio (v2), which is deprecated.

Learn how to migrate to the new Studio v3 β†’

schemas/object.js

import PreviewComponent from "../components/PreviewComponent";

export default {
  name: "steps",
  title: "Steps",
  type: "object",
  fields: [
    {
      name: "items",
      title: "Add Steps",
      type: "array",
      of: [
        {
          type: "object",
          fields: [
            {
              name: "title",
              title: "Title",
              type: "string"
            },
            {
              name: "description",
              title: "Description",
              rows: 3,
              type: "text"
            }
          ],
          preview: {
            select: {
              _key: "_key",
              title: "title",
              subtitle: "description"
            },
            prepare({ _key, title, subtitle }) {
              return { _key, title, subtitle };
            },
            component: PreviewComponent
          }
        }
      ]
    },
  ],
};

components/PreviewComponent.js

import React from "react";
import { withDocument } from "part:@sanity/form-builder";
import Preview from "part:@sanity/base/preview";

const PreviewComponent = ({ document, value }) => {
  const { steps } = document;
  const { _key, title, subtitle } = value;
  const index = steps.items.findIndex(item => item._key == _key);

  return (
    <Preview
      type="image"
      value={{
        title: title,
        subtitle: subtitle,
        media: <span style={{ fontSize: "1.5rem" }}>{index + 1}</span>
      }}
    />
  );
};

export default withDocument(PreviewComponent);

In this example, we created a custom PreviewComponent page to get the Index of an array item inside the object using the parent document and added the index as a custom image. But you can modify it to anything you like.

Contributor

Other schemas by author