Working with Rich Text and Svelte

In this post we’ll explore using GraphCMS Rich Text with Svelte.

Jamie Barton
Jamie Barton
graphcms rich text svelte

To follow along with this post you'll need: * A Svelte project already running, and connected to GraphCMS, * A model with a Rich Text field, and some content published.

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

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

npm install –save-exact @graphcms/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 @graphcms/rich-text-html-renderer exports the method astToHtmlString that we’ll need to import.

<script lang="ts">
import { astToHtmlString } from '@graphcms/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 '@graphcms/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](https://svelte.dev/tutorial/html-tags.

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

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

It's Easy To Get Started

GraphCMS plans are flexibly suited to accommodate your growth. Get started for free, or request a demo to discuss larger projects with more complex needs