I'm looking to replace an existing HTML editor with Lexical. I'm using the code from the web site to convert HTML to nodes as the starting point.
https://lexical.dev/docs/concepts/serialization
The data is being converted and the nodes are being generated.
However, get the following error when inserting the nodes?
Error: insertNode: topLevelElement is root node at RangeSelection.insertNodes (c:\Projects\ActivateV8\Activate.React.Web\ClientApp\node_modules\lexical\Lexical.dev.js:4002:1)
function SetDataPlugin ({model}) {
const [editor] = useLexicalComposerContext();
useEffect(() => {
if(!model) return;
editor.update(() => {
// In the browser you can use the native DOMParser API to parse the HTML string.
const parser = new DOMParser();
const dom = parser.parseFromString(model, "text/html");
// Once you have the DOM instance it's easy to generate LexicalNodes.
const nodes = $generateNodesFromDOM(editor, dom);
// Select the root
$getRoot().select();
// Insert them at a selection.
const selection = $getSelection();
selection.insertNodes(nodes);
});
}, [editor,model]);
}
Any help would be appreciated.
Got it working with the following code
editor.update(() => {
// In the browser you can use the native DOMParser API to parse the HTML string.
const parser = new DOMParser();
const dom = parser.parseFromString(model, "text/html");
// Once you have the DOM instance it's easy to generate LexicalNodes.
const nodes = $generateNodesFromDOM(editor, dom);
// Select the root
const root = $getRoot()
const paragraphNode = $createParagraphNode();
nodes.forEach((n)=> paragraphNode.append(n))
root.append(paragraphNode);
});