How can I add React component in the Draft.js and then display it?

86 Views Asked by At

I encountered the problem when React element was passing in Draft.js the app is break down, that’s why I convert it in appropriate format (convertFromRaw), then for display editing text I used to dangerouslySetInnerHTML.

Give me, please couple solutions to input dynamically data like: paragraph, heading, order list into Draft.js then display styled result on the page, preferable without dangerouslySetInnerHTML.

import { useState } from 'react';
import { EditorState, convertFromRaw } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';

const reactElementToContentState = (element) => {
  return convertFromRaw({
    entityMap: {},
    blocks: [
      {
        type: 'unstyled',
        text: element.props.children,
        key: 'foo',
        entityRanges: [],
      },
    ],
  });
};

export const Editors = () => {
  const initialContent = <p>Hello, this is a Draft.js content!</p>;

  const initialContentState = reactElementToContentState(initialContent);

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

  const [state, setState] = useState(null);

  const onEditorStateChange = (editorState) => {
    setEditorState(editorState);
  };
  const handleContentStateChange = (contentState) => {
    setState(contentState);
  };

  const contentStateHtml = draftToHtml(state);

  return (
    <div style={{ width: 600, border: '1px solid red' }}>
      <div style={{ border: '1px solid' }}>
        <Editor
          editorState={editorState}
          onEditorStateChange={onEditorStateChange}
          onContentStateChange={handleContentStateChange}
        />
      </div>
      <div dangerouslySetInnerHTML={{ __html: contentStateHtml }} />
    </div>
  );
};

I read these articles to understand what are approaches people use:

I tried pass unedited, not stylized React element - expected to see edited, styled. An additional, to get appropriate format of data for saving in DB in order to use later.

0

There are 0 best solutions below