I have implemented a rich text editor to React with the support of draftJs.
I am sending the editorState data to the server after converting to raw data and stringify it. That works well for rendering it to the front end.
Now, I want to take this data and update the editorState with this data. So, the user can edit the text with available data.
I don't, why it doesn't work. Please help me. I am not getting what should I do.
My code: Importing dependencies
import { Editor } from "react-draft-wysiwyg";
import { EditorState, ContentState, convertFromRaw, convertToRaw } from "draft-js";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
Initial State:
const [editorState, setEditorState] = useState(() =>
EditorState.createEmpty()
);
Trying to edit:
setEvent(current);
const data = JSON.parse(current.description);
// EditorState.createWithContent(convertFromRaw(data));
setEditorState(EditorState.createWithContent(ContentState.createFromText('Hello world')));
// EditorState.createWithContent(convertFromRaw(JSON.parse(current.description)));
// convertToRaw(JSON.parse(editorState.getCurrentContent()));
// const state = current.description;
// As per draft.js docs, I didn't understand the syntax
// convertFromRaw(rawState: state): ContentState
// EditorState.createWithContent(JSON.parse(current.description));
// setEditorState(JSON.parse(current.description));
Tried all this stuff. But, nothing updates the editorState
to current.description
.
Note: current.description
is a JSON string that contains raw object data.
Resources: createwithcontent
I have resolved the issue. Official DraftJs docs were a little confusing. It should have some examples. So, beginner and intermediate developers can get it.
I have done this:
setEditorState(EditorState.createWithContent(convertFromRaw(JSON.parse(current.description))));
I hope my effort would be helpful to others, and they don't need to waste their time like me.