To set a default content from a database in the react-draft-wysiwyg editor, you'll need to convert the content from the database to the proper format expected by the editor. The react-draft-wysiwyg editor works with ContentState, which is an immutable representation of the editor's content.

Assuming you have content stored in your database as a string, you'll need to convert it to a ContentState object. The process involves using the convertFromRaw function from the draft-js library to convert the raw JSON content to a ContentState object.

Here's a step-by-step guide on how to achieve this:

  1. Install the required libraries:
npm install draft-js react-draft-wysiwyg
  1. Import the necessary components and functions:
import React, { useState, useEffect } from 'react'; import { Editor } from 'react-draft-wysiwyg'; import { EditorState, convertToRaw, convertFromRaw } from 'draft-js'; import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
  1. Fetch the default content from the database:

Assuming you are fetching the default content from the database using an API call, you can use the useEffect hook to fetch the data and set it as the default content for the editor.

const EditorWithDefaultContent = () => { const [defaultContent, setDefaultContent] = useState(''); const [editorState, setEditorState] = useState(() => EditorState.createEmpty()); useEffect(() => { // Fetch the default content from the database (replace with your API call) // The content should be a JSON string representing the raw content fetchDefaultContentFromDatabase().then((response) => { if (response.success) { const rawContent = JSON.parse(; const contentState = convertFromRaw(rawContent); setEditorState(EditorState.createWithContent(contentState)); } }); }, []); const onEditorStateChange = (newEditorState) => { setEditorState(newEditorState); }; return ( <div> <Editor editorState={editorState} onEditorStateChange={onEditorStateChange} /> </div> ); }; export default EditorWithDefaultContent;

In this example, we use the useEffect hook to fetch the default content from the database. After receiving the data, we parse it as JSON and then convert it to a ContentState object using convertFromRaw. We set the initial editorState using the EditorState.createWithContent method, which will display the fetched content in the editor as the default value.

Now, the react-draft-wysiwyg editor will display the default content fetched from the database. Users can further edit the content as needed.

Have questions or queries?
Get in Touch