Load pre-existing html into Editor via React custom hook #3208
Answered
by
chalecki
tolkienfan2
asked this question in
Q&A
-
I am trying to load pre-existing html into my editor using a React hook in like this:
It isn't working. I would like to be able to pass in the returned value into the editorState parameter for the LexicalComposer initialConfig prop. |
Beta Was this translation helpful? Give feedback.
Answered by
chalecki
Dec 1, 2022
Replies: 1 comment
-
I faced the same challenge. I had to connect Lexical Editor as a Formik field. I end up creating a custom plugin 😎 import { $generateHtmlFromNodes, $generateNodesFromDOM } from '@lexical/html';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { CLEAR_HISTORY_COMMAND, $getRoot } from 'lexical';
import { useLayoutEffect } from 'react';
export const SetInitialValuePlugin: React.FC<{ initHtml: string }> = ({ initHtml = '' }) => {
const [editor] = useLexicalComposerContext();
useLayoutEffect(() => {
if (editor && initHtml) {
editor.update(() => {
const content = $generateHtmlFromNodes(editor, null);
if (!!initHtml && content !== initHtml) {
const parser = new DOMParser();
const dom = parser.parseFromString(initHtml, 'text/html');
const nodes = $generateNodesFromDOM(editor, dom);
const root = $getRoot();
root.clear();
const selection = root.select();
selection.removeText();
selection.insertNodes(nodes);
editor.dispatchCommand(CLEAR_HISTORY_COMMAND, null);
}
});
}
}, [initHtml]);
return null;
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
fantactuka
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I faced the same challenge. I had to connect Lexical Editor as a Formik field. I end up creating a custom plugin 😎