Rendering Content Relationship fields

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.

The Content Relationship field allows you to link to other Prismic documents in your repository and retrieve content from that document or add a link to that page of your site.

Rendering content from the Content Relationship

In the following example we are fetching the content from a document of the type "linked_page". In this case, the Content Relationship field has the API ID of related_content.

Copy
import React from 'react'
import { graphql } from 'gatsby'
import { RichText } from 'prismic-reactjs'

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.related_content.page_title)}
      </h1>
      <RichText render={document.related_content.description} />
    </>
  )
}

export const query = graphql`
  query {
    prismic {
      allPages(uid: "test-page") {
        edges {
          node {
            related_content {
              ... on PRISMIC_Linked_page {
                page_title
                description
              }
            }
          }
        }
      }
    }
  }
`

export default Page

Linking to a document from a Content Relationship

As mentioned before, Content Relationship field can be also used to link to documents and render links to that page. In the following example the field has the API ID document_link.

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

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

  return (
    <a href={Link.url(document.document_link, linkResolver)}>Go to page</a>
  )
}

export const query = graphql`
  query {
    prismic {
      allPages(uid: "test-page") {
        edges {
          node {
            document_link {
              _linkType
              ... on PRISMIC_Page {
                _meta {
                  uid
                }
              }
            }
          }
        }
      }
    }
  }
`

export default Page

Note that a Link Resolver is required when linking to a document, you can learn more about Link Resolver in this article.