Replies: 2 comments
-
try this
|
Beta Was this translation helpful? Give feedback.
0 replies
-
I was trying multiple ways to implement this, and ended up doing smth like this: const updateHTML = (editor: LexicalEditor, value: string, clear: boolean) => {
const root = $getRoot();
const parser = new DOMParser();
const dom = parser.parseFromString(value, "text/html");
const nodes = $generateNodesFromDOM(editor, dom);
if (clear) {
root.clear();
}
root.append(...nodes);
};
const prepopulatedRichText = (editor: LexicalEditor) => {
if (!defaultValue) return undefined;
updateHTML(editor, defaultValue ?? "", true);
};
const initialConfig = {
editorState: prepopulatedRichText,
namespace: "Playground",
nodes: [...DefaultNodes],
onError: (error: Error) => {
throw error;
},
theme: DefaultTheme
}; but I had a case where I have to wait for the API response, and add the value to the editor from one I saved in my DB so I edited the plugin I made to: import * as React from "react";
import { useEffect } from "react";
import { $generateNodesFromDOM } from "@lexical/html";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { $getRoot, LexicalEditor } from "lexical";
export default function LexicalDefaultValuePlugin({ value = "" }: { value?: string | null }) {
const [editor] = useLexicalComposerContext();
const updateHTML = (editor: LexicalEditor, value: string, clear: boolean) => {
const root = $getRoot();
const parser = new DOMParser();
const dom = parser.parseFromString(value, "text/html");
const nodes = $generateNodesFromDOM(editor, dom);
if (clear) {
root.clear();
}
root.append(...nodes);
};
useEffect(() => {
if (editor && value) {
editor.update(() => {
updateHTML(editor, value, true);
});
}
}, [value]);
return null;
} it will only change the editor value if the prop value changes, |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I want to set the default value of the editor from the preserved HTML after I get the value from the API response,
the code works only if I set the value statically,
I saw the examples, and setting the editor state does not work because I have to the HTML string in the database,
any help with the plugin?
Beta Was this translation helpful? Give feedback.
All reactions