Get a peek at our latest innovations at Sanity Product Day on Dec 8th →

Sanity internalLink render in React with Portable Text

By Surjith S M

Snippet for `internalLInk` Reference in GROQ and rendering it in React/Next.js frontend using Portabletext.

schemas/blockContent.js

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
                ]
              }
            ]
          },
        ]
      }
    },
  ]
};

Groq Query

import { groq } from "next-sanity";

export const postquery = groq`
*[_type == "post"] | order(_createdAt desc) {
  ...,
  category->,
    body[] {
      ...,
      markDefs[] {
        ...,
        _type == "internalLink" => {
          ...,
          "slug": @.reference-> slug
        }
      }
    }
}
`;

lib/sanity.js

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.

Contributor

Other schemas by author