I want to try DraftJS for my next project, where the scope varies from Admin panel pages' content, to users Posts, comments, and code snippets.
What are the options available to store data, like directly DraftJS state object, or parsing it to plain content, or some other way, how?
I am using draftJS as wysiwyg in a dashboard and i use to save the content as HTML, cause i use it for example in a news section of the website.
In first time import the related functions from the draft-js package.
import { EditorState, convertFromRaw, convertToRaw } from 'draft-js';
then when you would like to store it on your database just send it to your back end as html string.
const rawContentState = convertToRaw(this.state.editorState.getCurrentContent());
const HtmlContent = draftToHtml(rawContentState);
Now in HtmlContent you got your html text!
Sai Kishore Komanduri
Engineering an eGovernance Product | Hashnode Alumnus | I love pixel art
convertFromRawis a Draft utility function which can be used to convert the content state into a simple JS object, which represents the entire editor state, except for theSelectionStatedata.const rawContentState = convertToRaw( this.state.editorState.getCurrentContent() );You can β and it is the recommended way β directly store the raw content state from the above step, in your database; the reason being all the (meta)data you care about is there in the
rawContentStateobject.DraftJS has a helper
convertFromRawto convert the raw content state to the corresponding DraftJSContentState(immutable) data structure, and from there, into the desired editor state.const editorState = EditorState.createWithContent( convertFromRaw(rawContentState) );If you store HTML string as Davide suggests, you would have to take care of a few things, for example, making sure that the editor state is properly populated; you can use Draft's default
convertFromHTMLutility, but if you have custom blocks, then you have to augment the HTML parser to support them.A real-world example π
At Hashnode, we convert the entire editor state into Markdown, which is saved into the DB. To support this, we have two parsers, one which parses the DraftJS's editor state, and churns out the corresponding markdown; and second, which parses the markdown (on an edit), and churns out the corresponding editor state.
The reasons for going the markdown way were two fold:
For a post like this β React Tutorial using MERN Stack β we observed a ~25X improvement in data size; by opting for plain markdown instead of the editor object.