prefill html content inside lexical/react
editor
#2320
Answered
by
maltesa
harish-sethuraman
asked this question in
Q&A
-
import {$generateNodesFromDOM} from '@lexical/html';
// In the browser you can use the native DOMParser API to parse the HTML string.
const parser = new DOMParser();
const dom = parser.parseFromString(htmlString, textHtmlMimeType);
// In a headless environment you can use a package such as JSDom to parse the HTML string.
const dom = new JSDOM(htmlString);
// Once you have the DOM instance it's easy to generate LexicalNodes.
const nodes = $generateNodesFromDOM(editor, dom);
// Once you've generated LexicalNodes from your HTML you can now initialize an editor instance with the parsed nodes.
const editor = createEditor({ ...config, nodes });
// Or insert them at a selection.
const selection = $getSelection();
selection.insertNodes(nodes); I see that we need the editor instance to PS: Im using |
Beta Was this translation helpful? Give feedback.
Answered by
maltesa
Jul 21, 2022
Replies: 2 comments 26 replies
-
Hey bumping this in case it was missed |
Beta Was this translation helpful? Give feedback.
10 replies
-
I wrote this Plugin that loads my legacy HTML Content. Maybe that helps: import type { IRichText } from '@/components/RichTextEditor/types'
import { $generateNodesFromDOM } from '@lexical/html'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { $getRoot, CLEAR_HISTORY_COMMAND } from 'lexical'
import { useEffect } from 'react'
interface Props {
state?: string | IRichText
}
export function RestoreEditorStatePlugin({ state }: Props) {
const [editor] = useLexicalComposerContext()
useEffect(() => {
if (typeof state === 'string') {
// Restore from HTML (Quilljs legacy)
editor.update(() => {
const parser = new DOMParser()
const dom = parser.parseFromString(state, 'text/html')
const nodes = $generateNodesFromDOM(editor, dom)
const selection = $getRoot().select()
selection.insertNodes(nodes)
editor.dispatchCommand(CLEAR_HISTORY_COMMAND, undefined)
})
} else if (state?.editorState) {
// Restore from SerializedEditorState
const editorState = editor.parseEditorState(state.editorState)
editor.setEditorState(editorState)
editor.dispatchCommand(CLEAR_HISTORY_COMMAND, undefined)
}
}, [])
return null
} |
Beta Was this translation helpful? Give feedback.
16 replies
Answer selected by
thegreatercurve
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote this Plugin that loads my legacy HTML Content. Maybe that helps: