Skip to main content
Contentstack MCP profile hub is in general availability!

Rendering JSON RTE in React without surprises

•
11 min read

A JSON Rich Text Editor (JSON RTE) field arrives as a tree of nodes, not as HTML. That is what makes it useful: you decide how every paragraph, link and embedded entry renders. It is also where the surprises come from. Embedded items disappear without an error, React complains about hydration, and nested lists come out flat.

This guide is for React and Next.js apps that fetch content with the TypeScript Delivery SDK. It covers both ways to render the field: converting it to HTML with @contentstack/utils, and walking the JSON yourself to produce React components.

What you'll learn

  • Why embedded entries and assets render as nothing

  • When to use jsonToHTML and when to render nodes to React

  • How to avoid hydration errors from invalid nesting

  • How nested lists are stored and how to render them

  • How to add Live Preview edit tags to RTE fields

  • How to keep @contentstack/utils in step with the SDK

Symptoms

What you see

Most likely cause

Embedded entries or assets are missing from the output, no error

Fetched without includeEmbeddedItems()

In HTML, <div> cannot be a descendant of <p>. This will cause a hydration error.

A block element rendered inside a paragraph

validateDOMNesting(...): <div> cannot appear as a descendant of <p> (React 18)

Same cause, older React wording

Nested bullet points render as one flat list, or as <ul> directly inside <ul>

Nested lists are siblings of their list item in the JSON

The field is a string the second time you render it

jsonToHTML mutates the entry in place

Clicking the RTE in Live Preview does not open the field

No edit tag on the wrapper element

Type errors after upgrading the SDK or @contentstack/utils

Two versions of @contentstack/utils, or deep imports into dist

Why it happens

Contentstack concept: A JSON RTE value is a document node (type: "doc") with block children (p, h2, ul, table, ...), and text leaves at the bottom. A text leaf carries its marks as booleans: bold, italic, underline, strikethrough, inlineCode, superscript, subscript.

{
  "type": "doc",
  "children": [
    {
      "type": "p",
      "children": [
        { "text": "Read the " },
        { "text": "setup guide", "bold": true }
      ]
    },
    {
      "type": "reference",
      "attrs": {
        "type": "entry",
        "entry-uid": "blt8f1d2c3b4a596e7d",
        "content-type-uid": "author_card",
        "display-type": "block"
      },
      "children": [{ "text": "" }]
    }
  ]
}

The reference node does not contain the embedded entry. It only holds the UID and content type. The entry itself lives in _embedded_items on the parent entry, and only if you asked for it. Everything else in this guide follows from that split between the tree and the items it points to, and from the fact that the tree can describe nesting that HTML does not allow.

Fix it

Embedded entries and assets render as nothing

Call includeEmbeddedItems() on the entry or entries before you query:

import contentstack from '@contentstack/delivery-sdk';

const stack = contentstack.stack({
  apiKey: process.env.CONTENTSTACK_API_KEY as string,
  deliveryToken: process.env.CONTENTSTACK_DELIVERY_TOKEN as string,
  environment: process.env.CONTENTSTACK_ENVIRONMENT as string,
});

export async function getArticle(url: string) {
  const result = await stack
    .contentType('article')
    .entry()
    .includeEmbeddedItems()
    .query()
    .equalTo('url', url)
    .find();

  return result.entries?.[0];
}

includeEmbeddedItems() lives on entry(), not on the query object, so call it before query(). The response then has an _embedded_items object, keyed by field path, with the embedded entries and assets for each RTE field.

Without it, nothing fails. jsonToHTML looks up the item, finds nothing and renders an empty string for that node. When an embed is "just missing", check for _embedded_items in the raw response first.

On GraphQL, the field has a json value and an embedded_itemsConnection. Query both, and convert with GQL.jsonToHTML from @contentstack/utils, which reads the items from the connection.

jsonToHTML or React components

jsonToHTML converts the field to an HTML string. It is the shortest path when your RTE output is mostly prose:

import { jsonToHTML } from '@contentstack/utils';
import type { RenderOption } from '@contentstack/utils';

const escape = (value: string) =>
  value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);

const renderOption: RenderOption = {
  // Embedded entries shown as blocks, per content type
  block: {
    author_card: (item) =>
      `<aside class="author-card"><strong>${escape(item.title)}</strong></aside>`,
    $default: (item) => `<aside>${escape(item.title ?? item.uid)}</aside>`,
  },
  // Embedded assets shown as images
  display: (item, metadata) =>
    `<img src="${item.url}" alt="${escape(metadata.attributes.alt ?? item.title ?? '')}" loading="lazy" />`,
  // Override a regular node
  h2: (node, next) => `<h2 class="article-heading">${next(node.children)}</h2>`,
};

export function renderBody(article: { uid: string; body: unknown }) {
  const copy = structuredClone(article);
  jsonToHTML({ entry: copy, paths: ['body'], renderOption });
  return copy.body as string;
}
export function ArticleBody({ html }: { html: string }) {
  return <div className="prose" dangerouslySetInnerHTML={{ __html: html }} />;
}

A few things in that code are there on purpose:

  • paths is explicit. jsonToHTML only converts the fields you list. A field inside a group is 'group_uid.body'.

  • The entry is cloned. jsonToHTML replaces the JSON with the HTML string on the object you pass in. If that object came from a cache, the next render gets a string where it expects a tree.

  • Custom renderers escape values. The built-in renderers sanitize their output. Yours do not, so escape titles and attributes yourself.

  • The keys are display types. Embedded items use block, inline, link, display (an asset shown as an image) and download. Nodes use their type, such as p, a or h2.

Switch to rendering the JSON yourself when the output needs real components: next/link for internal links, a code block with a copy button, or design system components for embedded entries. You cannot get those from an HTML string.

Render nodes to React components

A React renderer is a recursive function: text leaves become text with marks, element nodes map to components, and anything unknown falls back to its children. This is a simplified version of the renderer developers.contentstack.com uses:

import Link from 'next/link';
import { Fragment, type ReactNode } from 'react';

type RteNode = {
  type?: string;
  text?: string;
  bold?: boolean;
  italic?: boolean;
  inlineCode?: boolean;
  attrs?: Record<string, any>;
  children?: RteNode[];
};

type EmbeddedItem = { uid: string; _content_type_uid?: string; [key: string]: any };

const blocks: Record<string, (children: ReactNode, node: RteNode, key: string) => ReactNode> = {
  p: (children, _node, key) => <p key={key}>{children}</p>,
  h2: (children, _node, key) => <h2 key={key}>{children}</h2>,
  h3: (children, _node, key) => <h3 key={key}>{children}</h3>,
  ul: (children, _node, key) => <ul key={key}>{children}</ul>,
  ol: (children, _node, key) => <ol key={key}>{children}</ol>,
  li: (children, _node, key) => <li key={key}>{children}</li>,
  blockquote: (children, _node, key) => <blockquote key={key}>{children}</blockquote>,
  a: (children, node, key) => {
    const href = node.attrs?.url ?? node.attrs?.href ?? '#';
    return href.startsWith('/') ? (
      <Link key={key} href={href}>{children}</Link>
    ) : (
      <a key={key} href={href} rel="noopener noreferrer">{children}</a>
    );
  },
};

function renderText(node: RteNode, key: string): ReactNode {
  let content: ReactNode = node.text;
  if (node.inlineCode) content = <code>{content}</code>;
  if (node.bold) content = <strong>{content}</strong>;
  if (node.italic) content = <em>{content}</em>;
  return <Fragment key={key}>{content}</Fragment>;
}

export function renderNode(
  node: RteNode,
  key: string,
  items: Map<string, EmbeddedItem>
): ReactNode {
  if (node.text !== undefined) return renderText(node, key);

  if (node.type === 'reference') {
    const uid = node.attrs?.['entry-uid'] ?? node.attrs?.['asset-uid'];
    const item = uid ? items.get(uid) : undefined;
    if (!item) return null;
    if (node.attrs?.type === 'asset') {
      return <img key={key} src={item.url} alt={node.attrs?.['asset-alt'] ?? item.title ?? ''} />;
    }
    return <EmbeddedEntry key={key} entry={item} />;
  }

  const children = foldNestedLists(node).map((child, i) =>
    renderNode(child, `${key}-${i}`, items)
  );
  const block = node.type ? blocks[node.type] : undefined;
  return block ? block(children, node, key) : <Fragment key={key}>{children}</Fragment>;
}

EmbeddedEntry is your own component that switches on entry._content_type_uid. Build the items map once per field from _embedded_items:

function embeddedItemsFor(entry: { _embedded_items?: Record<string, EmbeddedItem[]> }, path: string) {
  return new Map((entry._embedded_items?.[path] ?? []).map((item) => [item.uid, item]));
}

Keys built from the node's position in the tree (0-2-1) are stable between the server and the client, which matters for hydration. Do not use random IDs as keys.

Hydration errors from invalid nesting

React 19 reports it like this:

In HTML, <div> cannot be a descendant of <p>.
This will cause a hydration error.

This usually happens when a node that renders a block element sits inside a paragraph in the JSON. Editors insert an embedded entry or a captioned image in the middle of a paragraph, and the tree becomes p > reference. If your component for that reference returns a div, figure or aside, the server sends <p><div>…</div></p>. The browser closes the paragraph before the div, so the DOM no longer matches what React rendered.

The jsonToHTML default for a block entry also returns a div, so the same thing can happen with the HTML string inside a p.

Fix it in the renderer, not in the content:

const isBlockReference = (node: RteNode) =>
  node.type === 'reference' &&
  node.attrs?.['display-type'] !== 'link' &&
  node.attrs?.['display-type'] !== 'inline';

// Inside renderNode, before rendering a paragraph:
if (node.type === 'p' && node.children?.some(isBlockReference)) {
  return (
    <Fragment key={key}>
      {(node.children ?? []).map((child, i) => renderNode(child, `${key}-${i}`, items))}
    </Fragment>
  );
}

The paragraph unwraps when it holds a block-level embed. The same idea applies to other invalid nesting the RTE can produce, such as a table cell inside a table cell after an editor pastes a table into a cell. Render the inner cell's children in the outer cell.

Nested lists render flat

In the JSON, a nested list is not inside the list item it belongs to. It is the next sibling of that item:

{
  "type": "ul",
  "children": [
    { "type": "li", "children": [{ "text": "Install" }] },
    {
      "type": "ul",
      "children": [{ "type": "li", "children": [{ "text": "npm install" }] }]
    }
  ]
}

Rendered as-is, that is <ul><li>Install</li><ul>…</ul></ul>, which is invalid HTML. Since version 1.8.0, jsonToHTML in @contentstack/utils moves a nested list into the previous li. On an older version, or in your own React renderer, do the same:

function foldNestedLists(node: RteNode): RteNode[] {
  const children = node.children ?? [];
  if (node.type !== 'ul' && node.type !== 'ol') return children;

  const result: RteNode[] = [];
  for (const child of children) {
    const last = result[result.length - 1];
    const isList = child.type === 'ul' || child.type === 'ol';
    if (isList && last?.type === 'li') {
      result[result.length - 1] = { ...last, children: [...(last.children ?? []), child] };
    } else {
      result.push(child);
    }
  }
  return result;
}

Live Preview edit tags on RTE fields

Visual Builder and Live Preview find editable fields through data-cslp attributes. Add them to the entry with addEditableTags and spread the tag for the RTE field on the element that wraps its output:

import contentstack from '@contentstack/delivery-sdk';

if (isPreview) {
  contentstack.Utils.addEditableTags(article, 'article', true, locale);
}
<div className="prose" {...(article.$?.body ?? {})}>
  {article.body?.children?.map((node, i) => renderNode(node, String(i), items))}
</div>

With true as the third argument, the tags are objects like { 'data-cslp': 'article.blt….en-us.body' } that you can spread in JSX. Pass the entry's locale; the default is en-us. Tag the entry before you convert it with jsonToHTML, and only in preview, so production HTML stays clean. Edit tags and the Visual Editor covers edit tags in depth, and the Live Preview symptom index covers preview problems outside the RTE.

Version conflicts in @contentstack/utils

The TypeScript Delivery SDK depends on @contentstack/utils, and exposes it as contentstack.Utils. If you also install @contentstack/utils directly at another version, you get two copies with different types:

npm ls @contentstack/utils

If that lists two versions, align your direct dependency with the SDK's range (^1.9.1 for Delivery SDK 5.6), or drop it and use contentstack.Utils. Import types from the package root (import type { RenderOption, EntryModel } from '@contentstack/utils') instead of paths inside dist/types, which can move between releases.

Check that it worked

Check the data before the markup. Fetch the entry and confirm the embedded items are there:

curl -s "https://cdn.contentstack.io/v3/content_types/article/entries?environment=production&include_embedded_items[]=BASE&query=%7B%22url%22%3A%22%2Fmy-article%22%7D" \
  -H "api_key: $CONTENTSTACK_API_KEY" \
  -H "access_token: $CONTENTSTACK_DELIVERY_TOKEN" | jq '.entries[0]._embedded_items | keys'

You should see the RTE field's path in the list. Then load the page with the browser console open: no hydration warnings, embedded items visible, and nested lists indented. In Live Preview, hover the RTE output and confirm the edit button points at the right field.

Prevent it

  • Put includeEmbeddedItems() in the one function that fetches each content type with an RTE field.

  • Never pass cached entries to jsonToHTML. Clone first, or render the JSON directly.

  • Unwrap paragraphs that contain block-level embeds, and fold nested lists, in one shared renderer.

  • Add a test entry with every node type your editors use, and render it in CI to catch nesting warnings.

  • Keep one version of @contentstack/utils in your lockfile.

Key takeaways

  • A reference node only points at an item. Without includeEmbeddedItems(), it renders as nothing.

  • jsonToHTML mutates the entry and only converts the paths you list.

  • Block embeds inside p cause hydration errors. Unwrap the paragraph in your renderer.

  • Nested lists are siblings of their li in the JSON. Fold them into the previous item.

  • Spread entry.$.field on the RTE wrapper for Live Preview, and keep @contentstack/utils aligned with the SDK.

Frequently asked questions

  • Why do embedded entries in my JSON RTE render as nothing?

    The entry was fetched without includeEmbeddedItems(), so _embedded_items is missing. jsonToHTML cannot find the item and renders an empty string without an error.

  • Should I use jsonToHTML or render the JSON myself?

    Use jsonToHTML when HTML strings are enough. Render the JSON nodes yourself when you need React components such as next/link, code blocks with state or design system components.

  • Why does a JSON RTE field cause a hydration error?

    The output nests elements that HTML does not allow, such as a div inside a p. The browser fixes the DOM, React compares it with the server output, and the two no longer match.

  • Why are nested lists flat or invalid in my custom renderer?

    In the JSON, a nested list is a sibling of the list item it belongs to. jsonToHTML in @contentstack/utils 1.8.0 and later moves it into the previous list item. A custom renderer has to do the same.

  • Which @contentstack/utils version should I install?

    The one your Delivery SDK depends on. The TypeScript Delivery SDK 5.6 depends on @contentstack/utils ^1.9.1, and two copies of the package cause type conflicts.