Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draft js. Persist EditorContent to database

I'm trying to persist draft-js's EditorContent to database then read and recreate the EditorContent object again. But EditorContent.getPlainText() strips away rich text content. I don't know how else to do it.

How do I properly persist EditorContent?

like image 542
Dulguun Otgon Avatar asked Apr 08 '16 12:04

Dulguun Otgon


People also ask

Does draft JS support markdown?

Unfortunately, Draft. js doesn't natively Markdown and even if there are good initiatives, I didn't find a correct Draft/Markdown converter.

How does draft work Javascript?

To be efficient, Draft. js organizes set of consecutive characters w/ same styles(or same set of styles) in a single object called inlineStyleRanges. To be clear, this is ONLY organized like this in the “convertToRaw” output (for brevity). In actual contentState it is stored the long way for each character.

How do I convert Draftjs to HTML?

import React from "react"; import { Editor, EditorState } from "draft-js"; import { stateToHTML } from "draft-js-export-html"; class ExampleEditor extends React. Component { constructor(props) { super(props); this. state = { editorState: EditorState.


2 Answers

The getPlainText() method, as its name suggests, only returns the plain text without any rich formatting. You should use the convertToRaw() and convertFromRaw() functions to serialize and deserialize the contents of the editor.

You can import them this way if necessary: (assuming you are using ES6)

import {convertFromRaw, convertToRaw} from 'draft-js'; 

If you need to export HTML instead, see https://medium.com/@rajaraodv/how-draft-js-represents-rich-text-data-eeabb5f25cf2#9260 (not sure you can import the contents back from HTML, though)

like image 56
christophetd Avatar answered Oct 13 '22 19:10

christophetd


I've found that I must stringify and parse the RawContentState object when reading and saving to the database.

import { convertFromRaw, convertToRaw } from 'draft-js';  // the raw state, stringified const rawDraftContentState = JSON.stringify( convertToRaw(this.state.editorState.getCurrentContent()) ); // convert the raw state back to a useable ContentState object const contentState = convertFromRaw( JSON.parse( rawDraftContentState) ); 
like image 21
sealocal Avatar answered Oct 13 '22 18:10

sealocal