Watch a live product demo 👀 See how Sanity powers richer commerce experiences

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

One or the other validation

This validation can be used if you have two fields and you require one or the other to be filled

Roboto Studio
Go to One or the other validation

Easy peasy URL Slug

Studio v2

Quickly and easily validate your slug without having to work out the regex syntax

Roboto Studio
Go to Easy peasy URL Slug