HTML to DraftJS Converter
The `html-to-draftjs` library provides a utility function for converting raw HTML strings into a DraftJS `ContentState` object, which is suitable for direct use within a DraftJS editor. Currently stable at version `1.5.0`, this package is primarily designed to facilitate initial content loading or pasting functionalities in applications utilizing DraftJS, especially those built with `react-draft-wysiwyg`. While there's no explicit release cadence, the presence of recent version updates and a warning about a specific faulty version (1.2.0) indicates ongoing maintenance. Its key differentiator is its focused purpose for DraftJS, offering specific handling for HTML structures and an optional `customChunkRenderer` for extending its capabilities to handle custom HTML nodes or provide specific block types beyond standard conversions, particularly useful for atomic blocks.
Common errors
-
TypeError: htmlToDraft is not a function
cause Attempting to import `htmlToDraft` as a named export from a CommonJS context or incorrectly as a named import in an ESM context when it is a default export.fixFor ESM, use `import htmlToDraft from 'html-to-draftjs';`. For CJS, use `const htmlToDraft = require('html-to-draftjs').default;`. -
Error: Cannot find module 'html-to-draftjs'
cause The package has not been installed or is not correctly linked in your project's `node_modules`.fixRun `npm install html-to-draftjs` or `yarn add html-to-draftjs` in your project directory. -
Draft.js block 0: Missing data for block with type CUSTOM_BLOCK_TYPE
cause The `customChunkRenderer` returned a block type that is not recognized by your DraftJS editor, or the returned object is missing required properties.fixEnsure the `type` string returned by your `customChunkRenderer` matches a block type known to your DraftJS setup. Also, check that `mutability` and `data` (even if empty) are included in the returned object.
Warnings
- breaking Version `1.2.0` of `html-to-draftjs` is known to have build issues and should be avoided. Ensure you are using a different stable version.
- gotcha When using the `customChunkRenderer`, ensure that the `type` property returned matches a valid block type configured in your DraftJS editor. Incorrect types will result in rendering issues or errors.
- gotcha Complex or malformed HTML may not always convert perfectly to DraftJS ContentState, especially regarding inline styles, custom block data, and nested structures. The converter has limitations.
Install
-
npm install html-to-draftjs -
yarn add html-to-draftjs -
pnpm add html-to-draftjs
Imports
- htmlToDraft
import { htmlToDraft } from 'html-to-draftjs'; const htmlToDraft = require('html-to-draftjs');import htmlToDraft from 'html-to-draftjs';
Quickstart
import { EditorState, ContentState } from 'draft-js';
import htmlToDraft from 'html-to-draftjs';
// Example HTML content that might include custom elements
const htmlContent = '<p>This is <strong>rich</strong> HTML content.</p><hr/><p>Another paragraph.</p>';
// Optional: Define a custom chunk renderer for specific HTML nodes like <hr>
const blocksFromHtml = htmlToDraft(htmlContent, (nodeName, node) => {
if (nodeName === 'hr') {
return {
type: 'HORIZONTAL_RULE', // A custom block type defined in your DraftJS editor
mutability: 'IMMUTABLE',
data: {} // Optional data for the block
};
}
// Return nothing (or any falsy value) to let the default converter handle other nodes
return undefined;
});
if (blocksFromHtml) {
const { contentBlocks, entityMap } = blocksFromHtml;
const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap);
const editorState = EditorState.createWithContent(contentState);
console.log('Successfully converted HTML to DraftJS ContentState.');
console.log('Number of content blocks:', contentState.getBlocksAsArray().length);
console.log('First block text:', contentState.getFirstBlock().getText());
// In a React component, you would typically use `editorState` to initialize or update your DraftJS editor.
// Example: `this.setState({ editorState });`
} else {
console.error('Failed to convert HTML content. The input might be empty or invalid.');
}