birkir / gatsby-source-prismic-graphql

Gatsby source plugin for Prismic GraphQL
MIT License
137 stars 75 forks source link

Better Link Resolver Example #42

Open lusa opened 5 years ago

lusa commented 5 years ago

Hello, I just wanted to share this LinkResolver helper that I made because the current RichText in prismic-reactjs doesn't seem to work with the LinkResolver in this README - I've tried adding the snippet in gatsby-browser.js and could not get it to work. I then found out that I can use the RichText with serializeHyperlink from prismic-reactjs to conditionally render a Gatsby Link or a regular link if it's to an external URL. I think it would be great to either provide this example (or better one) on the README or somehow bake this into the library because it seems like something that should "just work", since Prismic gives you clear distinction between local document links and external links, it shouldn't require everyone to write custom code to render these embedded links in RichText.

import { Link } from "gatsby"
import { RichText } from "prismic-reactjs"
import React from "react"

export function LinkResolver(type, element, content, children, index) {
  if (element.data.link_type === "Web") {
    return <a href={element.data.url}>{content}</a>
  }
  return (
    <Link key={element.data.id} to={element.data.uid}>
      {content}
    </Link>
  )
}

// Usage
function PageContent({doc}) { 
    return <RichText render={doc} serializeHyperlink={LinkResolver} />
}
kimbui87 commented 5 years ago

In my case, RichText work with linkResolver when apply correctly these:

  1. Write a "linkResolver" follows https://prismic.io/docs/reactjs/beyond-the-api/link-resolving
  2. Set link_type for text in Prismic is "Link to Document" and destination is the matching linkResolver type.
  3. Add linkResolver when render RichText: < RichText render={text} linkResolver={linkResolver} /> "

You no need custom via serializeHyperlink.