Reputation: 993
I have a Lexical editor that needs to be serialized into html so that I can embed it in an email template.
I keep running into the following error when using the $generateHtmlFromNodes
function:
Error: Unable to find an active editor state.
State helpers or node methods can only be
used synchronously during the callback of editor.update() or editorState.read().
My Editor component takes one prop, the editorRef of type LexicalEditor, which ensures I have access to the editor from the parent, where I would like to handle the serialization and sending of the email.
Editor.tsx:
interface EditorProps {
editorRef: React.MutableRefObject<LexicalEditor>;
}
export const Editor = (props: EditorProps) => {
const initialConfig = {
namespace: 'MyEditor',
editable: true,
nodes: [ImageNode],
theme: <myTheme>,
onError(error) {
throw error;
},
};
return (
<div className="relative rounded-sm border border-gray-200 bg-white shadow-sm">
<LexicalComposer initialConfig={initialConfig}>
<Toolbar />
<ImagesPlugin />
<RichTextPlugin
contentEditable={
<ContentEditable
autoCorrect
className="min-h-[450px] resize-none overflow-hidden text-ellipsis py-[15px] px-2.5 outline-none"
/>
}
placeholder={null}
/>
<OnChangePlugin
onChange={(editorState, editor) => (props.editorRef.current = editor)}
/>
<HistoryPlugin />
</LexicalComposer>
</div>
);
};
My parent component:
export default function EmailClient() {
const editorRef = useRef<LexicalEditor>();
const handleSendEmail = () => {
const editor = editorRef.current;
const editorState = editor.getEditorState();
const jsonString = JSON.stringify(editorState);
console.log('jsonString', jsonString);
const htmlString = $generateHtmlFromNodes(editor, null);
console.log(htmlString);
};
return (
<Editor editorRef={editorRef} />
<Button
text="send"
function={handleSendEmail}
/>
);
}
Upvotes: 2
Views: 4863
Reputation: 993
After some digging on the Github issues I found a solution which is contrary to the examples in the lexical documentation.
It is necessary to wrap the $generateHtmlFromNodes
function in an editor.update
function as follows:
editor.update(() => {
const htmlString = $generateHtmlFromNodes(editor, null);
});
Upvotes: 7