2

The editor is starting as if it has empty string!

I tried this:

EditorState.createWithContent(ContentState.createFromText('Hello'))

and this:

const html = '<p>Hey this <strong>editor</strong> rocks 😀</p>';
const contentBlock = htmlToDraft(html);
if (contentBlock) {
  const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
  const editorState = EditorState.createWithContent(contentState);
  this.state = {
    editorState,
  };
}

and this:

import htmlToDraft from 'html-to-draftjs'
htmlToDraft(text)

nothing worked!

2 Answers 2

5

You don't show what you are doing with the content but the following (i.e. your first option) works correctly

<Editor
   editorState={EditorState.createWithContent(
          ContentState.createFromText("Hello")
     )}
/>

as does this:

import {
   Editor,
   EditorState,
   ContentState,
   convertFromHTML
} from "draft-js";

...

const blocksFromHTML = convertFromHTML(
  "<p>Hey this <strong>editor</strong> rocks 😀</p>"
);

const content = ContentState.createFromBlockArray(
  blocksFromHTML.contentBlocks,
  blocksFromHTML.entityMap
);

return (
      <Editor editorState={EditorState.createWithContent(content)} />
);
Sign up to request clarification or add additional context in comments.

Comments

1

In case you're interested, I've been bringing in HTML to the Editor for DraftJS via functional components. Here's that code built on top of @Grantnz's answer.

import React, { useState } from 'react'
import { Editor, EditorState, RichUtils, ContentState, convertFromHTML } from 'draft-js'

const DraftJS = () => {
    // assert hard-coded HTML string, convert it, bring it in as state
    const blocksFromHTML = convertFromHTML(
        "<p>Hey this <strong>editor</strong> rocks 😀</p>"
    );

    const content = ContentState.createFromBlockArray(
        blocksFromHTML.contentBlocks,
        blocksFromHTML.entityMap
    );

    const [editorState, setEditorState] = useState(EditorState.createWithContent(content));

    // handle changes to the Editor component
    const onChange = editorState => {
      setEditorState(editorState);
    }

    // build the Editor component
    return (
      <div>
        <h4 className="green-text">From DraftJS.js</h4>
        <Editor
          editorState={editorState}
          onChange={onChange}
        />
      </div>
    );
}

export default DraftJS;

Hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.