i.brod
i.brod

Reputation: 4603

How to insert HTML in Draft.js?

I'm using react-draft-wysiwyg editor, which is built on top of Draft.js. I'm trying to figure out, how to programmatically insert HTML, like:

<h1>Hey</h1>

So far, the closest thing i got is using the insertText() method of the Modifier module. Example:

insert = ()=>{
  const editorState = this.state.editorState;

  const selection = editorState.getSelection();

  const contentState = editorState.getCurrentContent();

  const ncs = Modifier.insertText(contentState, selection, "<h1>Hey</h1>",);

  const es = EditorState.push(editorState, ncs, 'insert-fragment');

  this.setState({editorState: es})
}

This results in a literal string being inserted, not an HTML H1 element.

How can it be done?

Upvotes: 5

Views: 11155

Answers (2)

N. Ahlers
N. Ahlers

Reputation: 394

I found a solution to the problem:

You can indeed use the "html-to-draftjs" library. Just use the "instert-fragment" and get the BlockMap of a temporary ContentState like the following:

import htmlToDraft from 'html-to-draftjs';
import { ContentState, EditorState, Modifier } from 'draft-js';

const data = "<h3>Dear member!</h3><p>This is a <b>TEST</b></p>"

let { contentBlocks, entityMap } = htmlToDraft(data);
let contentState = Modifier.replaceWithFragment(
   editorState.getCurrentContent(),
   editorState.getSelection(),
   ContentState.createFromBlockArray(contentBlocks, entityMap).getBlockMap()
 )

EditorState.push(editorState, contentState, 'insert-fragment')

Upvotes: 3

Gautam Naik
Gautam Naik

Reputation: 9358

In the react-draft-wysiwyg editor plugin docs here, at the end, it is mention, that, use HTML To DraftJS library for converting plain HTML to DraftJS Editor content.

Its a plugin made to work with react-draft-wysiwyg editor.

Link to Plugin here

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);

Upvotes: 4

Related Questions