From faa8cef66f20969365c75372cb064accfcc0b739 Mon Sep 17 00:00:00 2001 From: domtronn Date: Fri, 22 Nov 2019 10:53:09 +0000 Subject: [PATCH] feat: Add a backwards compatable version of toReactComponents This will allow you to pass a list of nodes, rather than requiring an entire document, and therefore allow rendering sub parts of the document tree. --- .../rich-text-react-renderer/src/index.tsx | 32 ++++++++++++++++--- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/packages/rich-text-react-renderer/src/index.tsx b/packages/rich-text-react-renderer/src/index.tsx index ec09b3d4..9e12b996 100644 --- a/packages/rich-text-react-renderer/src/index.tsx +++ b/packages/rich-text-react-renderer/src/index.tsx @@ -1,6 +1,6 @@ import React, { ReactNode } from 'react'; -import { Block, BLOCKS, Document, Inline, INLINES, MARKS, Text } from '@contentful/rich-text-types'; -import { nodeToReactComponent } from './util/nodeListToReactComponents'; +import { Block, BLOCKS, Document, TopLevelBlock, Inline, INLINES, MARKS, Text } from '@contentful/rich-text-types'; +import { nodeToReactComponent, nodeListToReactComponents } from './util/nodeListToReactComponents'; const defaultNodeRenderers: RenderNode = { [BLOCKS.DOCUMENT]: (node, children) => children, @@ -82,7 +82,31 @@ export function documentToReactComponents( return null; } - return nodeToReactComponent(richTextDocument, { + return toReactComponents(richTextDocument, nodeToReactComponent, options); +} + +/** + * Serialize a list of entities inside a Contentful Rich Text + * `document` to a react tree + */ +export function nodesToReactComponents( + richTextNodes: TopLevelBlock[], + options: Options = {}, +): ReactNode { + if (!richTextNodes || !richTextNodes.length) { + return null + } + + return toReactComponents(richTextNodes, nodeListToReactComponents, options); +} + +function toReactComponents( + nodes: any, + nodesToReactComponents: Function, + options: Options = {} +): ReactNode { + + return nodesToReactComponents(nodes, { renderNode: { ...defaultNodeRenderers, ...options.renderNode, @@ -92,5 +116,5 @@ export function documentToReactComponents( ...options.renderMark, }, renderText: options.renderText, - }); + }) }