I am retrieving content from Contentful using their Content Delivery API. My data contains a field with a rich text data type. I am using Contentful's rich-text-react-renderer to create the needed react components for elements in my rich text field. But when I add custom styling for BLOCK.PARAGRAPH, I find that overrides the styling I have added for BLOCK.QUOTE, BLOCK.UL_LIST, BLOCK.CODE, etc, which is not what I want. I want the paragraph styling to be the default only if another more specific block style is not present.
This seems to be because the blockquote data is returned with a paragraph node type nested inside the blockquote node.
Here is my rich text rendering function:
const richTextRenderParams: RichTextRenderOptions = {
renderNode: {
[INLINES.ENTRY_HYPERLINK]: (node: any, children: any) => styleArticleLink(node, children),
[INLINES.HYPERLINK]: (node, children) => <span>{children}</span>,
[BLOCKS.HEADING_2]: (node, children) => <Typography variant='h2'>{children}</Typography>,
[BLOCKS.HEADING_3]: (node, children) => <Typography variant='h3'>{children}</Typography>,
[BLOCKS.QUOTE]: (node, children) => <Typography sx={calloutStyle}>{children}</Typography>,
[BLOCKS.PARAGRAPH]: (node, children) => <Typography sx={bodyTextStyle}>{children}</Typography>,
},
};
return documentToReactComponents(body, richTextRenderParams);
This is the shape of the data returned from Contentful's Content Delivery API:
I would ask the paragraph function to apply only conditionally, but since it's inside the other node, I am not seeing a way to access the parent object to determine whether to apply the paragraph style or not.
This person seems to be having a similar issue: https://github.com/contentful/rich-text/issues/88
Reading comments there, I understood that I could remove the nested paragraph elements when processing the quotes, lists and other block styles.
I changed my handling of blockquotes (shown above) to instead be:
[BLOCKS.QUOTE]: (node, children) => <Typography sx={calloutStyle}>{removeParagraphWrapper(children)}</Typography>
The removeParagraphWrapper function looks like this:
const removeParagraphWrapper = (nodes: any) => {
if (nodes.length && nodes[0].props.children) {
return nodes[0].props.children
}
return nodes;
}
I did similar processing with lists and other styled blocks, and that worked for me. Now paragraph styles are not applied to block quotes, code blocks, or any other of Contentful rich test renderer's block styles.