Demo Blog
How to Render GraphCMS content
Kostas

Kostas

Dec 08, 2021

How to Render GraphCMS content

If you want to build a blog or any other similar website with GraphCMS, you need a way to render content coming from rich text editor.

First, I went with do it myself approach going through data layers and assigning html tags and styles to the content. GraphCMS raw content data structure is an array of objects with multiple layers. The code for going through data layers looks something like this:

{post.content.raw.children.map((typeObj, index) => {
		const children = typeObj.children.map((item, itemindex) =>
		getContentFragment(itemindex, item.text, item));
		return getContentFragment(index, children, typeObj, typeObj.type);
		})}

The getContentFragment function determines if the text is bold underlined or italic and applies html tags accordingly.

if (obj) {
			if (obj.bold) {
				modifiedText = <b key={index}>{text}</b>;
			}

			if (obj.italic) {
				modifiedText = <em key={index}>{text}</em>;
			}

			if (obj.underline) {
				modifiedText = <u key={index}>{text}</u>;
			}
		}

Then I use switch statement to return appropriate html and styling with tailwind. Part of the code for two types of content.

switch (type) {


		case 'paragraph':
		return (<p key={index} className='mb-8'>
		{modifiedText.map((item, i) => (
		<React.Fragment key={i}>{item}</React.Fragment>
		))}</p>);

		case 'heading-one':
		return (<h2 key={index} className='text-3xl font-semibold mb-4'>
		{modifiedText.map((item, i) => (
		<React.Fragment key={i}>{item}</React.Fragment>
		))}</h2>);

		default:
		return modifiedText;
		}

If you don't have more content that goes further then distinguishing between main text types html tags this approach works. But then I tried to add a link element that should be displayed as text.

Part of the data console.log(post.content.raw.children) looks something like this:

Huston we have a problem... The function cant distinguish that the text for the link is the last item of the array. The best solution I found was to use rich text renderer provided by GraphCMS. But on that a bit later.

Before trying to solve this I wanted to render good looking code blocks.

more coming soon ☺️

Kostas

Kostas

I'm a freshly baked web developer :)

Leave a comment ✍️

Related Posts

Categories