@nacelle/rich-text-html-renderer
v1.0.5
Published
Convert Rich Text field to HTML string
Downloads
1
Readme
rich-text-html-renderer
HTML renderer for the Rich Text field type.
Installation
Using npm:
npm install rich-text-html-renderer
Using yarn:
yarn add rich-text-html-renderer
Usage
import { render } from 'rich-text-html-renderer';
render({
schema: 'rast',
document: {
type: 'root',
children: [
{
type: 'paragraph',
children: [
{
type: 'span',
value: 'Hello world!',
},
],
},
],
},
}); // -> <p>Hello world!</p>
render({
type: 'root',
children: [
{
type: 'paragraph',
content: [
{
type: 'span',
value: 'Hello',
marks: ['strong'],
},
{
type: 'span',
value: ' world!',
marks: ['underline'],
},
],
},
],
}); // -> <p><strong>Hello</strong><u> world!</u></p>
You can pass custom renderers for nodes and text as optional parameters like so:
import { render, renderRule } from 'rich-text-html-renderer';
import { isHeading } from 'rich-text-utils';
const richText = {
type: 'root',
children: [
{
type: 'heading',
level: 1,
content: [
{
type: 'span',
value: 'Hello world!',
},
],
},
],
};
const options = {
renderText: (text) => text.replace(/Hello/, 'Howdy'),
customRules: [
renderRule(
isHeading,
({ adapter: { renderNode }, node, children, key }) => {
return renderNode(`h${node.level + 1}`, { key }, children);
},
),
],
};
render(document, options);
// -> <h2>Howdy world!</h2>
Last, but not least, you can pass custom renderers for entryLink
, inlineEntry
, block
as optional parameters like so:
import { render } from 'rich-text-html-renderer';
const graphqlResponse = {
value: {
schema: 'rast',
document: {
type: 'root',
children: [
{
type: 'paragraph',
children: [
{
type: 'span',
value: 'A ',
},
{
type: 'entryLink',
entry: '344312',
children: [
{
type: 'span',
value: 'record hyperlink',
},
],
},
{
type: 'span',
value: ' and an inline record: ',
},
{
type: 'inlineEntry',
entry: '344312',
},
],
},
{
type: 'block',
entry: '812394',
},
],
},
},
blocks: [
{
id: '812394',
image: { url: 'http://www.assets.com/1312/image.png' },
},
],
links: [{ id: '344312', title: 'Foo', slug: 'foo' }],
};
const options = {
renderBlock({ record, adapter: { renderNode } }) {
return renderNode('figure', {}, renderNode('img', { src: record.url }));
},
renderInlineRecord({ record, adapter: { renderNode } }) {
return renderNode('a', { href: `/blog/${record.slug}` }, record.title);
},
renderLinkToRecord({ record, children, adapter: { renderNode } }) {
return renderNode('a', { href: `/blog/${record.slug}` }, children);
},
};
render(document, options);
// -> <p>A <a href="/blog/foo">record hyperlink</a> and an inline record: <a href="/blog/foo">Foo</a></p>
// <figure><img src="http://www.assets.com/1312/image.png" /></figure>