Render html saved from draft-js

user4412054 picture user4412054 · Mar 8, 2018 · Viewed 8.6k times · Source

I'm learning React: totally newbie.

If I save in DB the HTML directly from draft.js (or it's variants always based on it) and then in a view page of my React SPA I retrieve HTML from DB through my API:

QUESTIONS:

Answer

Sandeep Mishra picture Sandeep Mishra · Mar 9, 2018

Draft-JS doesn't allows you to directly generate HTML from the present EditorState and that's a good thing. Since you are not dealing with "Raw HTML" you don't have to deal with XSS attacks as Draft Editors internal state won't get altered if someone inserts a script in the Editor.

Draft JS allows you the export the current Editor state so that you can store it easily. It can be done using

import {convertToRaw} from 'draft-js';

and in your onChange Handler you can simply do

const editorJSON = JSON.stringify(convertToRaw(EditorState.getContents()));

You can the store this JSON as you like for future use.

Now for Rendering this you have two options :

  1. Generate HTML from the stored EditorState.

    This can be done using Libraries like https://www.npmjs.com/package/draft-js-export-html. You might want to avoid this as the next option in my opinion is way better.

  2. Use this EditorState as the Default value for a read only DraftJS Editor Component.

    You are going to need convertFromRaw from DraftJS Library and then you make a Nice StateLess React Component like this

    import React from 'react';
    import {Editor, ConvertFromRaw} from 'draft-js';
    
    const ReadOnlyEditor = (props) => {
      const storedState =  ConvertFromRaw(JSON.parse(props.storedState));
      return (
         <div className="readonly-editor">
           <Editor editorState={storedState} readOnly={true} /> 
         </div>
      );
    }
    

    And Now you can simply use this to display your contents. You can also pass your decorators and custom mapping functions, typically everything you pass to the normal Editor and can render the content without loss of style and tedious dealing with HTML.