Easily restore your project to a previous version with our new Instant One-click Backup Recovery

Working with Rich Text and Svelte

In this post we’ll explore using Hygraph Rich Text with Svelte.
Jamie Barton

Jamie Barton

Jun 09, 2022
working with svelte and rich text

To follow along with this post you'll need:

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

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

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

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

Then inside of any of your Svelte routes you're fetching the model data that has a Rich Text field you will want to get the AST, and any 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-html-renderer exports the method astToHtmlString that we’ll need to import.

<script lang="ts">
import { astToHtmlString } from '@hygraph/rich-text-html-renderer';
</script>

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

<script lang="ts">
import { astToHtmlString } from '@hygraph/rich-text-html-renderer';
// const content = 'your query response for json/content'
// const references = 'your query response for references'
const html = astToHtmlString({
content,
references,
renderers: {
bold: props => `<strong>${props.children}</strong>`,
Asset: {
application: () => `<div><p>Asset</p></div>`,
text: () => `<div><p>text plain</p></div>`,
},
},
});
</script>

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

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 SvelteKit that you might want to default to providing extra attributes to an href such as sveltekit:prefetch.

Now all that’s left to do is invoke the Svelte @html tag to render our html. If you’ve used libraries like React, you can think of this similar to dangerouslySetInnerHTML. Learn more about the @html tag over on the Svelte docs.

<div>{@html html}</div>

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

Blog Author

Jamie Barton

Jamie Barton

Jamie is a software engineer turned developer advocate. Born and bred in North East England, he loves learning and teaching others through video and written tutorials. Jamie currently publishes Weekly GraphQL Screencasts.