Convert Lexical to HTML
Asked Answered
B

2

8

I am trying to export the content of my RTE developed with Lexical in HTML format. To do so, I have a button with an handleClick function which is supposed to console.log the content of the RTE in HTML.

When I try to export the content as a stringified JSON, there is no problem, I can see my content, for example:

{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"test content","type":"text","version":1}],"direction":"ltr","format":"","indent":0,"type":"paragraph","version":1}],"direction":"ltr","format":"","indent":0,"type":"root","version":1}}

However as soon as I try to convert the content to HTML, I keep having an empty string.

Any idea what I could be doing wrong here? Here is the function supposed to export the content to HTML:

import { $generateHtmlFromNodes } from '@lexical/html';

const handleClick = (editor: LexicalEditor) => {
  editor.update(() => {
    const editorState = editor.getEditorState();
    const jsonString = JSON.stringify(editorState);
    console.log('jsonString', jsonString);

    const htmlString = $generateHtmlFromNodes(editor);
    console.log('htmlString', htmlString);
  });
};

Thank you

Boatwright answered 21/7, 2022 at 8:14 Comment(3)
Show your $generateHtmlFromNodes implementationCrosstie
Hi @Justinas, github.com/facebook/lexical/blob/…Boatwright
How did you use the handleClick ? I am kind of confused by the document on how to finally wrap the the all text inside editor to make a http call.Whizbang
B
6

Finally found out what was the problem, the problem was that the function $generateHtmlFromNodes(editor, null) needs a second parameter as null, so the working solution is:

import { $generateHtmlFromNodes } from '@lexical/html';

const handleClick = (editor: LexicalEditor) => {
  editor.update(() => {
    const editorState = editor.getEditorState();
    const jsonString = JSON.stringify(editorState);
    console.log('jsonString', jsonString);

    const htmlString = $generateHtmlFromNodes(editor, null);
    console.log('htmlString', htmlString);
  });
};
Boatwright answered 22/7, 2022 at 14:6 Comment(1)
I think you don't need to do this now - April 2023. They have made it optional.Grave
S
3

Use a listener to get the latest update from the editor.

  React.useEffect(() => {
    const removeUpdateListener = editor.registerUpdateListener(
      ({ editorState }) => {
        editorState.read(() => {
          const htmlString = $generateHtmlFromNodes(editor, null);

          // Do something.
        });
      }
    );
    return () => {
      removeUpdateListener();
    };
  }, [editor]);
Stuppy answered 5/12, 2022 at 3:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.