Surjith S M
Web Designer & Front-end Developer. Figma, TailwindCSS & Next.js
Sanity preview component cannot access the parent/document if its inside an array or object. Using Custom Preview component, we can solve the issue.
This schema is for an older version of Sanity Studio (v2), which is deprecated.
Learn how to migrate to the new Studio v3 →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
}
}
]
},
],
};
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.
Web Designer & Front-end Developer. Figma, TailwindCSS & Next.js
Suppose you have an Array Reference to Category and you want to get all posts with one of the categories listed in the current post. This is usually when you need to get related items.
Go to Get related items of a post in sanity by comparing category array reference with another arrayA short snippet to filter category, tags or other document based on total referenced count.
Go to Sanity GROQ Filter category by highest reference count in other documentsSnippet for `internalLInk` Reference in GROQ and rendering it in React/Next.js frontend using Portabletext.
Go to Sanity internalLink render in React with Portable TextSanity provides various custom functions inside the schema. But getting a reference field value is difficult. Here's the how I do it using fetch.
Go to Get Sanity Reference Field Values inside Custom Schema Functions