Convert DatoCMS Structured Text field to HTML string
npm install datocms-structured-text-to-html-stringHTML renderer for the DatoCMS Structured Text field type.
Using npm:
``sh`
npm install datocms-structured-text-to-html-string
Using yarn:
`sh`
yarn add datocms-structured-text-to-html-string
`javascript
import { render } from 'datocms-structured-text-to-html-string';
render({
schema: 'dast',
document: {
type: 'root',
children: [
{
type: 'paragraph',
children: [
{
type: 'span',
value: 'Hello world!',
},
],
},
],
},
}); // ->
Hello world!
render({
type: 'root',
children: [
{
type: 'paragraph',
content: [
{
type: 'span',
value: 'Hello',
marks: ['strong'],
},
{
type: 'span',
value: ' world!',
marks: ['underline'],
},
],
},
],
}); // ->
Hello world!
You can pass custom renderers for nodes and text as optional parameters like so:
`javascript
import { render, renderNodeRule } from 'datocms-structured-text-to-html-string';
import { isHeading } from 'datocms-structured-text-utils';const structuredText = {
type: 'root',
children: [
{
type: 'heading',
level: 1,
content: [
{
type: 'span',
value: 'Hello world!',
},
],
},
],
};
const options = {
renderText: (text) => text.replace(/Hello/, 'Howdy'),
customNodeRules: [
renderNodeRule(
isHeading,
({ adapter: { renderNode }, node, children, key }) => {
return renderNode(
h${node.level + 1}, { key }, children);
},
),
],
customMarkRules: [
renderMarkRule('strong', ({ adapter: { renderNode }, children, key }) => {
return renderNode('b', { key }, children);
}),
],
};render(document, options);
// ->
Howdy world!
`Last, but not least, you can pass custom renderers for
itemLink, inlineItem, block as optional parameters like so:`javascript
import { render } from 'datocms-structured-text-to-html-string';const graphqlResponse = {
value: {
schema: 'dast',
document: {
type: 'root',
children: [
{
type: 'paragraph',
children: [
{
type: 'span',
value: 'A ',
},
{
type: 'itemLink',
item: '344312',
children: [
{
type: 'span',
value: 'record hyperlink',
},
],
},
{
type: 'span',
value: ' and an inline record: ',
},
{
type: 'inlineItem',
item: '344312',
},
],
},
{
type: 'block',
item: '812394',
},
],
},
},
blocks: [
{
id: '812394',
image: { url: 'http://www.datocms-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.image.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);
// ->
A record hyperlink and an inline record: Foo
// 
``