4

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

Pingolin
  • 3,161
  • 6
  • 25
  • 40
  • 1
    Show your `$generateHtmlFromNodes` implementation – Justinas Jul 21 '22 at 08:18
  • Hi @Justinas, https://github.com/facebook/lexical/blob/8cf834f02687ffa2825718487db40928b3caefd5/packages/lexical-html/src/index.ts#L54 – Pingolin Jul 21 '22 at 08:28
  • 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. – Jun Q Mar 30 '23 at 01:53

2 Answers2

3

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);
  });
};
Pingolin
  • 3,161
  • 6
  • 25
  • 40
1

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]);
Jalal
  • 3,308
  • 4
  • 35
  • 43