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
Sanity 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 FunctionsThis snippet will return only matched item in a sub array inside a document
Go to Sanity groq Filter by item in an arrayIt will expand the reference (projection) which is deeply linked in an array and optional using select funtion.
Go to Projection of a reference item in a deeplinked optional array.