@os-team/draft-to-html
v1.0.4
Published
Converts the Draft.js state (RawDraftContentState) to HTML.
Downloads
649
Readme
@os-team/draft-to-html
Converts the Draft.js state (RawDraftContentState) to HTML.
Usage
Install the package using the following command:
yarn add @os-team/draft-to-html
Simple usage
Import the draftToHtml
function and pass RawDraftContentState to value
.
import draftToHtml from '@os-team/draft-to-html';
const html = draftToHtml({ value: state });
Advanced usage
You can define how to convert any blocks, entities, and inline styles using blockRenderer
, entityRenderer
, and inlineStyleRenderer
respectively.
import draftToHtml from '@os-team/draft-to-html';
const html = draftToHtml({
value: state,
blockRenderer: (block, children) => {
// Render paragraphs as div
if (block.type === 'paragraph') {
return `<div>${children}</div>`;
}
// Render images
if (block.type === 'atomic:image') {
return `<img src="${block.data.src}" alt="${block.text}" />`;
}
return null;
},
entityRenderer: (entity) => {
// Render links
if (
entity.type === 'LINK' &&
entity.data &&
typeof entity.data.url === 'string'
) {
return `<a href="${entity.data.url}">${entity.text}</a>`;
}
return null;
},
inlineStyleRenderer: (inlineStyle) => {
// Render bold elements as span with the `bold` class name
if (inlineStyle.style === 'BOLD') {
return `<span class="bold">${inlineStyle.text}</span>`;
}
// Render custom inline style elements
if (inlineStyle.style === 'CUSTOM') {
return `<span class="custom">${inlineStyle.text}</span>`;
}
return null;
},
});