0
votes

I am using the library react-draft-wysiwyg, and I would like the inputted values from the text box to be in the form of an HTML string.

Currently, the inputted values that I log in the console appear in a format I can't submit to my backend, as it's expecting a string of HTML. I have tried using convertToRaw, but it doesn't seem to be changing the format of the data into what I would like.

My state:

editorState: EditorState.createEmpty

My editor JSX:

<Editor
 editorState={this.state.editorState}
 toolbarClassName="toolbarClassName"
 wrapperClassName="wrapperClassName"
 editorClassName="editorClassName"
 onEditorStateChange={this.onEditorStateChange}
/>

My onChange handler:

onEditorStateChange = (editorState) => this.setState({editorState});

And my handleSubmit function:

handleSubmit = async (event) => {
  event.preventDefault();
  const convertedData = 
        convertToRaw(this.state.editorState.getCurrentContent())

 //Followed by some code about posting to an API

Currently, when I look at what has been posted it looks like:

convertedData: {...}
   blocks: {...}
     0: {key: "174mo", text: "example text" etc... }
     1: {key: "5cdsn", text: "example text2" etc... }

With an array of all the formats of text that was entered. Is it possible to convert this into a string of HTML instead?

For example:

"
<h1>This is a header</h1>
<ul>List item</ul>
"

Thanks in advance for any help!

2
They have mentionend in their library that you can use json again back to show the real html and also have provided the library github.com/jpuri/draftjs-to-html can be used to convert RawDraftContentState to html. github.com/jpuri/html-to-draftjs provides the option to convert HTML generated by react-draft-wysiwyg back to draftJS ContentState which can be used to initialize the Editor. For more check this url jpuri.github.io/react-draft-wysiwyg/#/docs?_k=jjqinp and scroll to the bottom.somsgod

2 Answers

0
votes

You should import draftToHtml.

import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs'; 

handleSubmit = async (event) => {
  event.preventDefault();
  const convertedData = 
        draftToHtml(convertToRaw(this.state.editorState.getCurrentContent()));    
0
votes

It works 100%

import { convertToHTML } from 'draft-convert';

const submitHandler = useCallback((event) => {
        event.preventDefault();
        const convertedData = convertToHTML(data.editor1.getCurrentContent());
});