Reputation: 257
I'm using DraftJS to edit text contents, but when I tried to edit any existing contents that I've retrieved from DB and loaded into the Editor, the cursor auto jumps to the beginning of the texts and I started typing from backwards.
I've imported the Editor
into Bulletin.js
, so I have to get the content by passing getContent
into Editor
and retrieve back the raw html by using getContent
in the handleEditorChange
function of the Editor
.
I've found out that if I've removed the getContent
function to pass back the raw HTML in handleEditorChange
, the editor works normally, but then I won't be able to get the html content back to Bulletin.js
.
Here's the codesandbox that I've created for reference.
Upvotes: 1
Views: 1917
Reputation: 183
The issue is that you set on every change a new EditorState
here:
useEffect(() => {
if (htmlContent) {
let convertedToHTML = decodeURIComponent(htmlContent);
const blocksFromHtml = htmlToDraft(convertedToHTML);
const { contentBlocks, entityMap } = blocksFromHtml;
const contentState = ContentState.createFromBlockArray(
contentBlocks,
entityMap
);
setEditorState(EditorState.createWithContent(contentState));
}
}, [htmlContent]);
htmlContent
is always changing as you convert the EditorState
to HTML on every change via the getContent
function.
If you want to initialize your EditorState
with the htmlContent
you can do it in the useState
function and remove the useEffect
:
const [editorState, setEditorState] = useState(() => {
if (htmlContent) {
let convertedToHTML = decodeURIComponent(htmlContent);
const blocksFromHtml = htmlToDraft(convertedToHTML);
const { contentBlocks, entityMap } = blocksFromHtml;
const contentState = ContentState.createFromBlockArray(
contentBlocks,
entityMap
);
return EditorState.createWithContent(contentState);
}
return EditorState.createEmpty()
});
Upvotes: 3