Link Resolving

Prismic no longer recommends the gatsby-source-prismic-graphql plugin

With recent changes to Gatsby, Prismic no longer recommends the gatsby-source-prismic-graphql plugin that this documentation uses. Read more about the future of Prismic and Gatsby. We highly recommend using the gatsby-source-prismic instead. The documentation for this plugin can be found in the plugin's github README.

We will leave this documentation here for now, but will change it in the future when we determine the best approach for Prismic & Gatsby.

When working with field types such as a Link or a Rich Text in a Gatsby project, you will need an easy way to generate links to documents within your website.

Since routing is specific to your site, you will need to define all your routes in a Link Resolver function and pass it to any methods or fields that require it.

Start by creating the /src/utils/linkResolver.js file. This example helps resolving your page routes dynamically for three document types (category, product, and page). You will need to adapt it or write your own depending on the routes in your own website.

Copy
export const linkResolver = (doc) => {
  // URL for a category type
  if (doc.type === 'category') {
    return `/category/${doc.uid}`
  }

  // URL for a product type
  if (doc.type === 'product') {
    return `/product/${doc.uid}`
  }

  // URL for a page type
  if (doc.type === 'page') {
    return `/${doc.uid}`
  }

  // Backup for all other types
  return '/'
}

Now let's register the link resolver. We just need to update the gatsby-browser.js file in your root directory and add this code to it.

Copy
import { registerLinkResolver } from '@prismicio/gatsby-source-prismic-graphql'
import { linkResolver } from './src/utils/linkResolver'

registerLinkResolver(linkResolver)

Now let's see how you can use the Link Resolver that we previously created and registered in your Gatsby project.

Copy
import React from 'react'
import { graphql, Link } from 'gatsby'
import { RichText } from 'prismic-reactjs'
import { linkResolver } from '@prismicio/gatsby-source-prismic-graphql'

const GatsbyLink = (type, element, content, children, index) => {
  if (element.data.link_type === 'Document') {
    return (
      <Link to={linkResolver(element.data)} key={element.data.id}>
        {content}
      </Link>
    )
  }
  return null
}

const Page = ({ data }) => {
  const prismicContent = data.prismic.allPages.edges[0]
  if (!prismicContent) return null
  const document = prismicContent.node

  return (
    <>
      <h1 className="page-title">
        {RichText.asText(document.title)}
      </h1>
      <RichText
        render={document.description}
        serializeHyperlink={GatsbyLink}
      />
    </>
  )
}

export const query = graphql`
query {
  prismic {
    allPages(uid: "test-page") {
      edges {
        node {
          title
          description
        }
      }
    }
  }
}
`

export default Page