Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@contentful/rich-text-react-renderer

contentful1.9mMIT16.0.1TypeScript support: included

React renderer for the Contentful rich text field type.

readme

rich-text-react-renderer

React renderer for the Contentful rich text field type.

Installation

Using npm:

npm install @contentful/rich-text-react-renderer

Using yarn:

yarn add @contentful/rich-text-react-renderer

Usage

import { documentToReactComponents } from '@contentful/rich-text-react-renderer';

const document = {
  nodeType: 'document',
  data: {},
  content: [
    {
      nodeType: 'paragraph',
      data: {},
      content: [
        {
          nodeType: 'text',
          value: 'Hello world!',
          marks: [],
          data: {},
        },
      ],
    },
  ],
};

documentToReactComponents(document); // -> <p>Hello world!</p>
import { documentToReactComponents } from '@contentful/rich-text-react-renderer';

const document = {
  nodeType: 'document',
  content: [
    {
      nodeType: 'paragraph',
      content: [
        {
          nodeType: 'text',
          value: 'Hello',
          marks: [{ type: 'bold' }],
        },
        {
          nodeType: 'text',
          value: ' world!',
          marks: [{ type: 'italic' }],
        },
      ],
    },
  ],
};

documentToReactComponents(document);
// -> <p><b>Hello</b><u> world!</u></p>

You can also pass custom renderers for both marks and nodes as an optional parameter like so:

import { BLOCKS, MARKS } from '@contentful/rich-text-types';
import { documentToReactComponents } from '@contentful/rich-text-react-renderer';

const document = {
  nodeType: 'document',
  content: [
    {
      nodeType: 'paragraph',
      content: [
        {
          nodeType: 'text',
          value: 'Hello',
          marks: [{ type: 'bold' }],
        },
        {
          nodeType: 'text',
          value: ' world!',
          marks: [{ type: 'italic' }],
        },
      ],
    },
  ],
};

const Bold = ({ children }) => <p className="bold">{children}</p>;

const Text = ({ children }) => <p className="align-center">{children}</p>;

const options = {
  renderMark: {
    [MARKS.BOLD]: (text) => <Bold>{text}</Bold>,
  },
  renderNode: {
    [BLOCKS.PARAGRAPH]: (node, children) => <Text>{children}</Text>,
  },
  renderText: (text) => text.replace('!', '?'),
};

documentToReactComponents(document, options);
// -> <p class="align-center"><p class="bold">Hello</p><u> world?</u></p>

Last, but not least, you can pass a custom rendering component for an embedded entry:

import { BLOCKS } from '@contentful/rich-text-types';
import { documentToReactComponents } from '@contentful/rich-text-react-renderer';

const document = {
  nodeType: 'document',
  content: [
    {
      nodeType: 'embedded-entry-block',
      data: {
        target: (...)Link<'Entry'>(...);
      },
    },
  ]
};

const CustomComponent = ({ title, description }) => (
  <div>
    <h2>{title}</h2>
    <p>{description}</p>
  </div>
);

const options = {
  renderNode: {
    [BLOCKS.EMBEDDED_ENTRY]: (node) => {
      const { title, description } = node.data.target.fields;
      return <CustomComponent title={title} description={description} />
    }
  }
};

documentToReactComponents(document, options);
// -> <div><h2>[title]</h2><p>[description]</p></div>

The renderNode keys should be one of the following BLOCKS and INLINES properties as defined in @contentful/rich-text-types:

  • BLOCKS

    • DOCUMENT
    • PARAGRAPH
    • HEADING_1
    • HEADING_2
    • HEADING_3
    • HEADING_4
    • HEADING_5
    • HEADING_6
    • UL_LIST
    • OL_LIST
    • LIST_ITEM
    • QUOTE
    • HR
    • EMBEDDED_ENTRY
    • EMBEDDED_ASSET
    • EMBEDDED_RESOURCE
  • INLINES

    • EMBEDDED_ENTRY (this is different from the BLOCKS.EMBEDDED_ENTRY)
    • EMBEDDED_RESOURCE
    • HYPERLINK
    • ENTRY_HYPERLINK
    • ASSET_HYPERLINK
    • RESOURCE_HYPERLINK

The renderMark keys should be one of the following MARKS properties as defined in @contentful/rich-text-types:

  • BOLD
  • ITALIC
  • UNDERLINE
  • CODE

The renderText callback is a function that has a single string argument and returns a React node. Each text node is evaluated individually by this callback. A possible use case for this is to replace instances of \n produced by Shift + Enter with <br/> React elements. This could be accomplished in the following way:

const options = {
  renderText: (text) => {
    return text.split('\n').reduce((children, textSegment, index) => {
      return [...children, index > 0 && <br key={index} />, textSegment];
    }, []);
  },
};

Note on adding a key prop in custom renderers:

It is possible to pass a key prop in the components returned by custom renderers. A good use case for this is in embeded entries using the node's target.sys.id. It is important not to pass anything that is index-like (e.g. 1 or "1") as it may clash with the default renderers which automatically inject a key prop using their index in the Contentful rich text AST.

To work around this limitation, just append any non-numeric character to your custom key.

const options = {
  renderMark: {
    [MARKS.BOLD]: (text) => {
      return <b key={`${text}-key`}>{text}</b>;
    },
  },
};

Preserving Whitespace

The options object can include a preserveWhitespace boolean flag. When set to true, this flag ensures that multiple spaces in the rich text content are preserved by replacing them with &nbsp;, and line breaks are maintained with <br /> tags. This is useful for content that relies on specific formatting using spaces and line breaks.

Note that preserveWhitespace is not compatible with the renderText option. When the functionality of preserveWhitespace is desired along with a custom renderText callback, it should be implemented within the callback instead.

import { documentToReactComponents } from '@contentful/rich-text-react-renderer';

const document = {
  nodeType: 'document',
  content: [
    {
      nodeType: 'paragraph',
      content: [
        {
          nodeType: 'text',
          value: 'Hello     world!',
          marks: [],
        },
      ],
    },
  ],
};

const options = {
  preserveWhitespace: true,
};

documentToReactComponents(document, options);
// -> <p>Hello&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;world!</p>

In this example, the multiple spaces between "Hello" and "world!" are preserved in the rendered output.

changelog

Change Log

All notable changes to this project will be documented in this file. See Conventional Commits for commit guidelines.

15.15.1 (2022-11-30)

Bug Fixes

15.15.0 (2022-11-29)

Bug Fixes

Features

  • adding v1 marks to rich text types [TOL-786] (#416) (8885de8)

15.14.1 (2022-11-23)

Note: Version bump only for package @contentful/rich-text

15.14.0 (2022-11-14)

Features

15.13.2 (2022-09-07)

Bug Fixes

  • add --no-package-lock (#364) (41643c9)
  • add inline sources to packages (#357) (bca6abb)
  • add missing -- to circleci release commands (#360) (233be08)
  • add prettier write command (#345) (0edad4c)
  • circleci update resource class (#359) (6bb3710)
  • revert change to monorepo tsconfig, apply to tsconfig in rich-text-types (#358) (56126cc)
  • update Lerna, rollup in slatejs-adapter (#366) (32448e3)

15.13.1 (2022-05-10)

Bug Fixes

15.13.0 (2022-05-06)

Features

  • support converting tables from markdown to rich-text (0abc0c6)

15.12.1 (2022-04-21)

Bug Fixes

  • upgrade react peerDependencies to support react^18.0.0 (#323) (7a0bfdf)

15.12.0 (2022-03-25)

Features

  • enforce minItems in table-related node types (#314) (1125331)

15.11.2 (2022-02-07)

Bug Fixes

  • set "typings" for rich-text-from-markdown (1b3a15f)

15.11.1 (2022-01-04)

Bug Fixes

15.11.0 (2021-12-27)

Bug Fixes

  • react-renderer: wrap table rows in tbody (#300) (e23d1f4)

Features

  • rich-text-types: expose HEADINGS array (#301) (758539d)

15.10.1 (2021-12-21)

Bug Fixes

  • remove support to convert tables from md to rich text (a9d513c)

15.10.0 (2021-12-15)

Features

15.9.1 (2021-12-10)

Bug Fixes

  • rich-text-types: resolve generated JSON schemas (#294) (1e5b4c4)

15.9.0 (2021-12-09)

Features

  • rich-text-types: expose RT validation helper (#292) (fc5a7cc)

15.8.0 (2021-11-11)

Features

  • add toContentfulDocument() and toSlatejsDocument() empty block node handling (#287) (fa79626)

15.7.0 (2021-11-11)

Features

  • rich-text-types: Add TEXT_CONTAINERS (#286) (3356ea8)

15.6.2 (2021-11-05)

Note: Version bump only for package @contentful/rich-text

15.6.1 (2021-11-05)

Note: Version bump only for package @contentful/rich-text

15.6.0 (2021-11-04)

Features

  • add support to convert tables from md to rich text (#284) (213a29c)

15.5.1 (2021-10-25)

Bug Fixes

15.5.0 (2021-10-25)

Features

15.4.0 (2021-09-16)

Features

15.3.6 (2021-09-15)

Bug Fixes

  • allow table-row type to have both cells (#267) (ec40598)

15.3.5 (2021-09-13)

Bug Fixes

  • rich-text-types: forbid Tables inside ListItem (#266) (fc338bf)

15.3.4 (2021-09-09)

Bug Fixes

  • replace import to fix typings for html-renderer (#265) (40c2670)

15.3.3 (2021-09-07)

Note: Version bump only for package @contentful/rich-text

15.3.2 (2021-09-07)

Note: Version bump only for package @contentful/rich-text

15.3.1 (2021-09-07)

Note: Version bump only for package @contentful/rich-text

Change Log

15.3.0 (2021-09-06)

Bug Fixes

  • allow the first item in Table to be a TableHeaderRow (9a6de55)
  • don't export the helper TableHeaderRow type (179c3cb)
  • typo (2282665)

Features

  • add TableHeaderCell type (5e25ac9)

15.2.0 (2021-08-16)

Bug Fixes

  • 🐛 html encode default inlined CF entry/asset links (41396eb)
  • 🐛 prevent html injection via data.uri link rendering (ecae89a)
  • audit fix aiming mixing-deep vulnerability (2b98cbd)
  • audit fix root folder (ffe9e44)

15.1.0 (2021-08-02)

Features

  • 🎸 add RT html renderer tables support (ce81375)
  • 🎸 add RT react renderer tables support (fddfb8a)
  • add rowspan (e0264fb)

15.0.0 (2021-06-15)

Bug Fixes

  • slatejs-adapter: release as public package (#227) (0ba8197)

Features

  • add table markup support (c6ae127)

14.2.0 (2021-05-04)

Features

  • {wip} update slate.js adapter (c281aea)
  • fix test types (0c86f93)
  • update contentful-to-slatejs adapter (33a3b6d)
  • update contentful-to-slatejs-adapter (89a32f4)

14.1.3 (2021-04-12)

14.1.2 (2020-11-02)

Bug Fixes

  • 🐛 configure rollup copy correctly (3446a33)
  • 🐛 skip lib check for TS (e8bf2ba)
  • Add leaf object (#5) (fb0b80d)
  • Add lodash.omit to externals (#7) (1c65200)
  • Remove doc deployment and fix (90bccaa)

Features

  • Add a default value for Marks (6828215)
  • Add data transform (#6) (9d90fa1)
  • Cleans up the mark property from extra props (20ec641)
  • contentful-to-slate: Implement new isVoid in Slate's Node (3d2d38d)
  • data defaults to an empty object (0a9b8a0)
  • first version (11591d0)
  • integrate structured-text-types (#8) (d6d5e37)
  • remove content from void nodes (0ce9898)
  • Remove nodeClass from Contentful's Document (23bb2d5)
  • update dependencies (e294233)
  • Update structured-text-type version (#9) (ced65da)

Performance Improvements

  • ⚡️ Remove lodash.omit dependency (93b6b76)

BREAKING CHANGES

  • Remove nodeClass from Contentful's Document
  • Changed the interface of Slate->Contentful adapter. Added new parameter Schema
  • contentful-to-slate: toSlatejsDocument now accepts Schema
  • Only supports structured-text-types >= 2.0.0

14.0.1 (2020-01-30)

Features

  • 🎸 emptyDoc representing an empty RT document (80315ef)

14.0.0 (2020-01-28)

Bug Fixes

  • 🐛 detect links as children of nodes also having links (565f423)

13.4.0 (2019-08-01)

Features

  • 🎸 Adds BLOCKS.DOCUMENT renderer support to react-renderer (57c922c), closes #104

13.3.0 (2019-03-21)

13.2.0 (2019-03-18)

Features

  • 🎸 renderText option to alter all text (f684a6e)

13.1.0 (2019-03-04)

Bug Fixes

  • 🐛 Fix incorrect typings file path (cca74d5)

Features

  • 🎸 Support filtering by node name in rich-text-links (5ec0dda)

13.0.1 (2019-02-11)

Bug Fixes

  • 🐛 Fix wrong import in tests (bead583)
  • 🐛 make "time to read" great again (6edd37d)

Features

  • 🎸 Initial rich-text-react-renderer implementation (06dad9b)

13.0.0 (2019-01-22)

Bug Fixes

  • 🐛 use named export instead of default (57bf365)

BREAKING CHANGES

  • removes default export from 'rich-text-plain-text-renderer'

12.2.1 (2019-01-22)

Bug Fixes

  • gracefully handle empty rich text documents (14870de)

Features

  • 🎸 add time to read for reach text (5f2115a)

12.2.0 (2018-12-20)

Bug Fixes

Features

  • 🎸 parse links inside marks (11722cf)

12.1.2 (2018-12-14)

Bug Fixes

Features

12.1.1 (2018-12-12)

Bug Fixes

12.1.0 (2018-12-12)

Bug Fixes

  • async-handling: move to promise-based api (a07d3fc)

12.0.4 (2018-12-05)

Bug Fixes

  • Add index.js (383cc98)
  • package: add babel/runtime to deps; remove 'main' from package.json (f7adbff)
  • package: use caret operator for gatsby peer dep (21478ef)

12.0.3 (2018-12-05)

Bug Fixes

  • build: rm gatsby from dev-deps on gatsby plugin (2b3f87b)
  • deps: dep to old version within monorepo (b0da60a)
  • readme: mark types in readme examples (d997b56)
  • Remove debugger (c7c9c4f)

Features

  • transformer: Add gatsby-transformer-contentful-richtext (8ed2adb)

Performance Improvements

  • ⚡️ prefer iterator unrolling to Array.from (a887a92)

12.0.2 (2018-12-04)

Bug Fixes

  • 🐛 update path to typings (ce5544f)

12.0.1 (2018-12-04)

Bug Fixes

  • 🐛 add Object.values and Array.prototype.includes polyfills (9e2ffb4)
  • from-markdown: Fix list typos (c392016)
  • parsing: list item, (un)ordered list, links, quotes (8a0c580)
  • text: Parse text nodes with marks correctly (d489f90)

12.0.0 (2018-11-29)

Features

  • 🎸 getRichTextEntityLinks perf and signature changes (fcd6d7f)

Performance Improvements

  • ⚡️ Add benchmark support (ae278b7)

BREAKING CHANGES

  • Produces an entirely new return value and obviates the linkType parameter (all entities are grouped and returned by default).

11.0.0 (2018-11-27)

Bug Fixes

  • 🐛 Removes cz-lerna-changelog from devDependencies (31daac0)
  • 🐛 Removes obsolete field title from Hyperlinks (8cb9027)

10.3.0 (2018-11-26)

Features

  • 🎸 return all entity links when no linkType is provided (02970ea)

10.2.0 (2018-11-19)

Features

  • 🎸 Add rich-text-references (363b4e5)
  • 🎸 Rename, refactor, docu. & cache r-t-links (9cf6d14)

10.1.0 (2018-11-16)

Bug Fixes

  • 🐛 removes obsolete fields from mark nodes (b638a56)

Features

  • 🎸 adds json schema generation to rich text types (8916140)
  • 🎸 introduces top-level-block type (a6bf35e)

10.0.5 (2018-11-12)

Bug Fixes

  • 🐛 handle case of missing rootNode / rootNode.content (e2434c7)

10.0.4 (2018-11-09)

10.0.3 (2018-11-09)

10.0.2 (2018-11-09)

10.0.1 (2018-11-08)

Features

  • packages: Add rich text from markdown package (bc8ec41)

10.0.0 (2018-11-02)

Features

  • 🎸 removes nodeClass from Node interface (09b8162)

BREAKING CHANGES

  • Removes accidentally added nodeClass

9.0.2 (2018-10-31)

9.0.1 (2018-10-31)

9.0.0 (2018-10-30)

Bug Fixes

  • 🐛 Fix block divisor provision (3aafb7a)
  • 🐛 remove exclusive mocha test (5ff5d0e)

Features

  • 🎸 Explicitly declare nodeClass and nodeType in core types (0749c61)

BREAKING CHANGES

  • Fundamentally alters the plain text renderer behavior. (For the better!)
  • Potentially breaks TypeScript libraries pulling this in as a dependency if they are not explicitly stating nodeClass and nodeType.

8.0.3 (2018-10-30)

8.0.2 (2018-10-29)

8.0.1 (2018-10-26)

Bug Fixes

  • 🐛 Revert mock hypenation commits (bde9432)
  • sync HTML renderer (769bd95)

Features

  • 🎸 take all packages out of "demo mode" (815f18b)

BREAKING CHANGES

  • renames all packages

7.0.1 (2018-10-26)

Bug Fixes

  • 🐛 hypenate more hyperlink tokens (f88b377)

7.0.0 (2018-10-26)

Bug Fixes

  • 🐛 blockquote -> block-quote (5b66181)
  • 🐛 hyphenate hyper-link (662f60d)
  • 🐛 Remove .releaserc.js (f1f72a7)

chore

  • 🤖 :%s/ci/travis (4731881)
  • 🤖 swap for semantic-release-monorepo (cb8ca3e)

BREAKING CHANGES

  • major version bump
  • None, but let's pretend like there are some anyway to trigger a major version bump

6.0.0 (2018-10-24)