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
?
Unfortunately, Draft. js doesn't natively Markdown and even if there are good initiatives, I didn't find a correct Draft/Markdown converter.
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.
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.
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)
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) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With