Render html saved from draft-js
Asked Answered
R

3

7

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:

Roslynrosmarin answered 8/3, 2018 at 13:47 Comment(0)
A
10

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.getCurrentContent()));

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.

Apanage answered 9/3, 2018 at 16:13 Comment(2)
The function to get state contents is getCurrentContent() now: draftjs.org/docs/api-reference-editor-state#getcurrentcontentDoubtless
load all those scripts when are rendering from server side is affect your performance to response.Illimani
S
4

DO NOT Believe USERS!

The first thing you should care of is "Do NOT believe your USERS".

If your 'HTML' is rendered by your server and can't be modified by user, it's totally OK. Because your rendered/saved HTML is totally safe and managed by yourself, and if it's assured as "SAFE" HTML, whether you put it(html) into DOM or not is not the problem at all.

But the problem is, most of WYSIWYG editors - like draft.js- makes "HTML" files not TEXT. I think your worry comes from here too.

Yes, It's dangerous. what we can do is NOT rendering HTML directly but "selective" HTML rendering.

Dangerous tags : <script>, <img>, <link>, etc.

you can remove those tags but it can be much safer when you decide which tags will you allow, like this:

Safe tags: <H1> - <H6> / span / div / p / ol ul li / table...

and you SHOULD remove those HTML element's attributes, like, onclick="", etc.

because it could be abused by users too.

Conclusion:

So what can we do when we use WYSIWYG editors?

There are 2 big strategies:

  1. Generate "Safe" HTML when safe to Database.
  2. Generate "Safe" HTML before putting it into DOM. (3. Generate "Safe" HTML before sending html to client, but it is not in your case!)

Choose first one if you want to sure Database's text are totally safe.

First one must be processed in your server(not browser/client!), and you can use many solutions like BeautifulSoup in python, or sanitize-html in nodejs.

Choose second one if your web-app is complicated, and most of your service's business logic is running on front-end side.

Second one is using HTML escaping package just before mounting HTML into DOM. and still sanitize-html can be good solution. (surelly there's more great solutions!) You can decide which tags/attribute/values in HTML.


Links

https://github.com/punkave/sanitize-html

Solorzano answered 8/3, 2018 at 14:41 Comment(5)
Ok. Thanks a lot. And for render html in react? What about those packages?Roslynrosmarin
@JohnSam umm, could you tell me more specific? I couldn't understand your comment ;)Solorzano
In my question I ask: “dangerouslySetInnerHTML? Or maybe one of this (what do you suggest?)?”Roslynrosmarin
You're safe to use innerHTML when you generate filtered(safe) html ;)Solorzano
just make your html SAFE before mounting component.Solorzano
C
1

in 2022 for me, it works a bit different way

import { convertFromRaw, Editor, EditorState } from 'draft-js';

function Comments() {
const itemText= EditorState.createWithContent(convertFromRaw(JSON.parse(item.content)));

return <Editor editorState={itemText} readOnly={true} />

}

and to the DB it was saved like that

JSON.stringify(convertToRaw(editorState.getCurrentContent()))

the difference is that for me without EditorState it doesn't work, I believe that I am not alone in that

Catima answered 8/12, 2022 at 15:38 Comment(1)
Same here it works for me 2023. Thank you!Freeholder

© 2022 - 2024 — McMap. All rights reserved.