I'm creating a component that will display the data from backend by using draft-js. The data from the backend also is being stored using draft-js. The data is not being display and also there's no error message.
Sample Data from the backend is being parse before passing to the viewContent.js
Hello World
I tried to create a variable to check if the code is working. I tried this approach const sample = <p>Hello World
. This one is working if pass this on contenBlocks.
viewContent.js
import {
EditorState,
ContentState,
convertFromHTML,
} from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
const viewContent = ({ content }) => {
const contentBlocks = convertFromHTML(content);
const contentState = ContentState.createFromBlockArray(
contentBlocks.contentBlocks,
contentBlocks.entityMap
);
const [editorState, setEditorState] = useState(() =>
EditorState.createWithContent(contentState)
);
const handleEditorChange = (state) => {
setEditorState(state);
let currentContentAsHTML = JSON.stringify(
draftToHtml(convertToRaw(editorState.getCurrentContent()))
);
};
return (
<div className='comment-container p-2 border rounded-md'>
<Editor
editorState={editorState}
onEditorStateChange={handleEditorChange}
wrapperClassName='wrapper-class'
editorClassName='editor-class'
toolbarClassName='toolbar-class'
/>
</div>
);
};
export default viewContent;
CodePudding user response:
You should set editor state after ViewContent
component rendered completely. update your component as below:
...
useEffect(() => {
const contentBlocks = convertFromHTML(content);
const contentState = ContentState.createFromBlockArray(
contentBlocks.contentBlocks,
contentBlocks.entityMap
);
setEditorState(EditorState.createWithContent(contentState));
}, [content]);
...