Sanity Custom Preview Component to get Parent Document
Studio v2
Sanity preview component cannot access the parent/document if its inside an array or object. Using Custom Preview component, we can solve the issue.
By Surjith S M
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

Surjith S M
Web Designer & Front-end Developer. Figma, TailwindCSS & Next.js
India