VPR
VPR

Reputation: 165

How can I convert html to draftjs?

I have tried basic packages but I don't seem to get whats going on,

Here is something that I tried;

const {
  convertFromHTML,
  ContentState
} = require('draft-js');
const htmlToDraft = require('html-to-draftjs');

const converter = () => {
    const sampleMarkup =
      '<b>Bold text</b>, <i>Italic text</i><br/ ><br />' +
      '<a href="http://www.google.com">Example link</a>';

    const blocksFromHTML = convertFromHTML(sampleMarkup);
    const state = ContentState.createFromBlockArray(blocksFromHTML);

    console.log('state: ', state);
}

converter();

It was really clear on which library to use. I am getting weird looking outputs, what I expect looks something like this;

{
  "blocks": [
    {
      "depth": 0,
      "inlineStyleRanges": [
        {
          "length": 9,
          "style": "BOLD",
          "offset": 0
        },
        {
          "length": 12,
          "style": "ITALIC",
          "offset": 11
        }
      ],
      "entityRanges": [
        {
          "length": 12,
          "key": 0,
          "offset": 25
        }
      ],
      "data": {},
      "text": "Bold text, Italics text\n\nexample link ",
      "key": "9jc4q",
      "type": "unstyled"
    }
  ],
  "entityMap": {
    "0": {
      "type": "LINK",
      "mutability": "MUTABLE",
      "data": {
        "url": "http://www.google.com",
        "targetOption": "_blank"
      }
    }
  }
}

Any insights ? (code in server side )

Upvotes: 3

Views: 11309

Answers (2)

Anand Barasara
Anand Barasara

Reputation: 21

I am following the code and my code is running fine. I don't have any problem, you can check by copying my code.

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


const htmlToDraftBlocks = (html) => {
 const blocksFromHtml = htmlToDraft(html);
 const { contentBlocks, entityMap } = blocksFromHtml;
 const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap);
 const editorState = EditorState.createWithContent(contentState);
 return editorState;
}


useEffect(()=>{
setEditorState(htmlToDraftBlocks("<p>Hello</p>"));
},[])

Upvotes: 2

Makwana Prahlad
Makwana Prahlad

Reputation: 969

const sampleMarkup =
  '<b>Bold text</b>, <i>Italic text</i><br/ ><br />' +
  '<a href="http://www.facebook.com">Example link</a>';

const blocksFromHTML = convertFromHTML(sampleMarkup);
const state = ContentState.createFromBlockArray(
  blocksFromHTML.contentBlocks,
  blocksFromHTML.entityMap,
);

this.state = {
  editorState: EditorState.createWithContent(state),
};

Upvotes: 3

Related Questions