How to render Draft-js text in React from server

Viewed 1105

I using Draft-js to build my text-editor. enter image description here

What I want to do is on clicking the submit button, the submitted text should appear on right side (as you can see, the blank side)

I'm calling a handleSubmit function to post the content to server:

handleSubmit = e => {

        e.preventDefault();

        const query = JSON.stringify(convertToRaw(this.state.editorState.getCurrentContent()));

        const payload = {
            query:query
        }

        axios({
            url:'http://localhost:9000/queries',
            method:'POST',
            data: payload
        })
        
    }

and to retrieve the content :

getQueries(){
        axios.get("http://localhost:9000/queries")
        .then(response => {
            const data = response.data;
            this.setState({queries:data});
        })
    } 

I'm bit confused, on how to use convertFromRaw to convert the content to the desired text.

Where should I call the method ?

Thanks in advance

1 Answers

You have to understand that DraftJS is a library that converts whatever you have inside the editor into it own format.

For Example, apple is converted to,

{
    "blocks": [{
        "key": "f6b3g",
        "text": "apple",
        "type": "unstyled",
        "depth": 0,
        "inlineStyleRanges": [{
            "offset": 0,
            "length": 5,
            "style": "ITALIC"
        }],
        "entityRanges": [],
        "data": {}
    }],
    "entityMap": {}
}

Yep, it's that big. So, in order to convert it back from this format to apple you need a component which knows how to interpret it. You cannot just use a div tag. In this case, it's the editor component itself!

So you can do the following to display the content in readonly mode.

<Editor readOnly={true}
  editorState={EditorState.createWithContent(this.state.editorState.getCurrentContent())}/>

Now, say if you want to send the editor contents to an API so that you can save it in DB and then get the content from the API and display it.

  1. Convert from Editor Format to JSON
const requestBody = JSON.stringify(convertToRaw(this.state.editorState.getCurrentContent()))
  1. Post JSON to your API
fetch(url, {
  method: 'POST',
  body: requestBody
});
  1. Get JSON from your API
const response = await fetch(url, {
  method: 'GET'
});
  1. Convert from JSON to Editor format and display using Editor (You can remove readonly if you want the user to edit the contents)
<Editor readOnly={true}
  editorState={EditorState.createWithContent(convertFromRaw(JSON.parse(response))}/>
Related