Next.js Conf 2024: Your app should be Live by Default – Watch Keynote

Internal/External Next.js Link

By Roboto Studio

Internal/External link based on the conditional field example with Next.js component starters

Sanity Schema

export default {
  name: "customUrl",
  title: "Custom URL",
  type: "object",
  fields: [
    {
      name: "external",
      type: "url",
      title: "URL",
      hidden: ({ parent, value }) => !value && !!parent?.internal,
    },
    {
      name: "internal",
      type: "reference",
      to: [{ type: "page" }, { type: "article" }, { type: "homePage" }],
      hidden: ({ parent, value }) => !value && !!parent?.external,
    },
  ],
};

Next.js Component

import React from "react";
import Link from "next/link";


export default ({ href, children }) => {
  return (
    <>
      {href?.internal ? (
        <Link href={href.internal.slug.current}>{children}</Link>
      ) : href?.external ? (
        <a href={href.external}>{children}</a>
      ) : null}
    </>
  );
};

Next.js TypeScript Component

import React from "react";
import Link from "next/link";

interface CustomLinkSchema {
  href: any;
  children: any;
  passHref?: any;
}

export default ({ href, children, ...props }: CustomLinkSchema) => {
  return (
    <>
      {href?.internal ? (
        <Link href={href.internal.slug.current} {...props}>
          {children}
        </Link>
      ) : href?.external ? (
        <a href={href.external}>{children}</a>
      ) : null}
    </>
  );
};

We took the original Sanity conditional field for internal/external links, and built it into an object.

https://www.sanity.io/docs/conditional-fields#eda5e1b778e3

We've also included an example for routing with Next/Link inside of a Next.js website. We are currently using this within the Roboto Studio site, with some added complexity, but we kept this version as stripped down as possible for a good starting point.

Contributor

Other schemas by author

Cursor Prompt

Thinking about getting started with AI? Well we're just going to share our latest and greatest prompt so you don't have to do the hard work

Go to Cursor Prompt

Portable Text Mock Content

If you're looking to mockup portable text in Storybook without a Sanity backend, this is the schema you're looking for

Go to Portable Text Mock Content