Search code examples
draftjsmentiondraft-js-plugins

Draft.js Mention Plugin is not working after rendering contentState to the editor


I am using mentions with the draft.js (like this @yourname) and sending to the database to save and fetching it to render on the web page but things are not working as expected.

On Saving to the database ->

const contentState = editorState.getCurrentContent();
const currentStateData = convertToRaw(contentState);
const richStringifyValue = JSON.stringify(currentStateData);
// sending richStringifyValue to save in Mongo DB

On Fetch and set in editor ->

const [editorState, setEditorState] = React.useState(() => EditorState.createEmpty());
const parsedData = JSON.parse(post.contentStyled);
const fromRawData = convertFromRaw(parsedData );
EditorState.createWithContent(fromRawData);


// here is the view rendered part -
   <Editor 
     readOnly={true}
     editorState={editorState}
   />

But after setting in editor (after the data fetched from API) my mentions (@... @... @...) lost the CSS. What should we do?

On Using Edit -> enter image description here

On fetch and setting again in Editor -> enter image description here

I don't know why is that happening, please help to resolve this issue!


Solution

  • You should do the following:

    const [editorState, setEditorState] = React.useState(() => {
      const parsedData = JSON.parse(post.contentStyled);
      const fromRawData = convertFromRaw(parsedData );
      return EditorState.createWithContent(fromRawData);
    });
    
    // ...
       <Editor 
         readOnly={true}
         editorState={editorState}
       />
    

    If you override the editorState with a new created state you are removing all the decorators which were added by the plugins.