Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Lexical to HTML

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

like image 481
Armel Avatar asked May 18 '26 12:05

Armel


2 Answers

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);
  });
};
like image 50
Armel Avatar answered May 21 '26 03:05

Armel


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]);
like image 45
Jalal Avatar answered May 21 '26 03:05

Jalal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!