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 [editorState, setEditorState] = useState();
const clearState = () => {
ContentState.createFromText('');
};
const handleEditorChange = (state) => {
setEditorState(state);
let currentContentAsHTML = JSON.stringify(
draftToHtml(convertToRaw(editorState.getCurrentContent()))
);
convertedContent(currentContentAsHTML);
};
useEffect(() => {
const contentBlocks = convertFromHTML(content);
const contentState = ContentState.createFromBlockArray(
contentBlocks.contentBlocks,
contentBlocks.entityMap
);
setEditorState(EditorState.createWithContent(contentState));
}, [content]);
return (
<div className='comment-container p-2 border rounded-md'>
<Editor
editorState={editorState}
onEditorStateChange={handleEditorChange}
wrapperClassName='wrapper-class'
editorClassName='editor-class'
toolbarClassName='toolbar-class'
onClick={clearState}
/>
</div>
);
};
export default viewContent;
Parent Compontent
<viewContent
content={taskInfo.taskNote}
convertedContent={(convertedContent) =>
setTaskInfo((prevState) => ({
...prevState,
taskNote: convertedContent,
}))
}
/>
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]);
...