HTML to DraftJS Converter

1.5.0 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

Demonstrates how to convert an HTML string to DraftJS ContentState, including using the optional customChunkRenderer for specific HTML tags like `<hr/>`.

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.');
}

view raw JSON →