What is html-to-draftjs?
The html-to-draftjs npm package is a utility that converts HTML markup into Draft.js ContentState, which is a data structure used by the Draft.js editor framework. This allows developers to easily integrate HTML content into Draft.js editors.
What are html-to-draftjs's main functionalities?
Convert HTML to Draft.js ContentState
This feature allows you to convert HTML strings into Draft.js ContentState, which can then be used to initialize or update the state of a Draft.js editor.
const htmlToDraft = require('html-to-draftjs').default;
const { ContentState, EditorState } = require('draft-js');
const html = '<p>Hello, world!</p>';
const contentBlock = htmlToDraft(html);
const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
const editorState = EditorState.createWithContent(contentState);
console.log(editorState);
Other packages similar to html-to-draftjs
draft-js-import-html
The draft-js-import-html package provides similar functionality by converting HTML to Draft.js ContentState. It offers more customization options and supports a wider range of HTML tags and attributes compared to html-to-draftjs.
draft-convert
The draft-convert package is another alternative that provides utilities for converting between Draft.js ContentState and HTML. It offers a more flexible API and supports both import and export operations, making it a versatile choice for handling HTML and Draft.js conversions.
HTML To DraftJS
A library for converting plain HTML to DraftJS Editor content.
Build for use with react-draft-wysiwyg.
Installation
npm install html-to-draftjs --save
Usage
import { EditorState, ContentState } from 'draft-js';
import htmlToDraft from 'html-to-draftjs';
const blocksFromHtml = htmlToDraft(this.props.content);
const { contentBlocks, entityMap } = blocksFromHtml;
const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap);
const editorState = EditorState.createWithContent(contentState);
(optional) customChunkRenderer
Use to define additional html nodes. Only supports atomic blocks.
- nodeName: string - the name of the node, in lowercase
- node: HTMLElement - the parsed node itself
This renderer function is executed before any other html to draft conversion.
Return nothing (or something falsy) to continue with the normal translation.
Example:
htmlToDraft('<hr/>', (nodeName, node) => {
if (nodeName === 'hr') {
return {
type: 'HORIZONTAL_RULE',
mutability: 'MUTABLE',
data: {}
};
}
})
Take Care: Plz not use version 1.2.0
it has build issues.