Working with Rich Text and React

In this post we’ll explore using Hygraph Rich Text with React.

Jamie Barton
Jamie Barton

To follow along with this post you'll need:

  • A React project already running, and connected to Hygraph,
  • A model with a Rich Text field, and some content published.

If you’re new to React and Hygraph this video should show how to get started:

Start by installing the @hygraph/rich-text-react-renderer dependency within your project.

npm install –save-exact @hygraph/rich-text-react-renderer

Then inside of your React app, you'll want to fetch the content from your Hygraph project, and the Rich Text field. I'll leave the exact implementation up to you, but you'll want to fetch the AST, and the embedded references.

Your query may look something like:

query GetPosts {
pages {
content {
json
references {
... on Post {
id
title
}
... on Asset {
url
width
height
}
}
}
}
}

If you'd prefer to follow along with some sample data, you can find that here.

The @hygraph/rich-text-react-renderer exports the component RichText that we’ll need to import:

import { RichText } from '@hygraph/rich-text-react-renderer';

We'll now take the Rich Text AST (json + references) and convert it to HTML, providing the references, and custom renderers using the RichText component:

export default function App() {
return (
<RichText
content={content}
references={references}
renderers={{
h1: ({ children }) => <h1 className={`wfafsa`}>{children}</h1>,
a: ({ children, href, openInNewTab }) => (
<a
href={href}
target={openInNewTab ? '_blank' : '_self'}
style={{ color: 'green' }}
rel="noreferrer"
>
{children}
</a>
),
bold: ({ children }) => <strong>{children}</strong>,
Asset: {
text: () => (
<div>
<p>text plain</p>
</div>
),
},
}}
/>
</div>
)
}

You'll see above we can pass custom renderers to RichText.

This means you can override the default HTML element for what's to be shown in the Rich Text. This is extremely useful for things like links in Next.js where you will want to use the next/link component. You'll want to create a custom renderer for your Asset types.

That’s it! You will now see the Rich Text output with any custom renderers applied.