Surjith S M
Web Designer & Front-end Developer. Figma, TailwindCSS & Next.js
Snippet for `internalLInk` Reference in GROQ and rendering it in React/Next.js frontend using Portabletext.
export default {
title: "Block Content",
name: "blockContent",
type: "array",
of: [
{
title: "Block",
type: "block",
marks: {
annotations: [
{
name: "internalLink",
type: "object",
title: "Internal link",
fields: [
{
name: "reference",
type: "reference",
title: "Reference",
to: [
{ type: "post" }
// other types you may want to link to
]
}
]
},
]
}
},
]
};
import { groq } from "next-sanity";
export const postquery = groq`
*[_type == "post"] | order(_createdAt desc) {
...,
category->,
body[] {
...,
markDefs[] {
...,
_type == "internalLink" => {
...,
"slug": @.reference-> slug
}
}
}
}
`;
export const PortableText = props => (
<PortableTextComponent
components={{
marks: {
internalLink: ({ children, value }) => {
return (
<Link href={`/post/${value.slug.current}`}>
<a> {children}</a>
</Link>
);
}
}
}}
{...props}
/>
);
If you have created a portable text for react and you want to render an internal link from other post, you can use this code.
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 documentsSanity preview component cannot access the parent/document if its inside an array or object. Using Custom Preview component, we can solve the issue.
Go to Sanity Custom Preview Component to get Parent DocumentSanity 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