How we can get html from editorState in Lexical rich editor?

Viewed 206

I want to generate HTML format from editorState in Lexical Rich Editor, I'm able to get selection with editorState and what will be best to save into database, HTML or some sort of JSON format?

and I want to show this HTML outside of editor. here is some example of code

const onChange = (editorState) => {
  const editorStateTextString = editorState.read(() => {
    const selection = $getSelection();
    
    console.log(selection);

    return $getRoot().getTextContent();
  });

  // TODO: saving text only at the moment
  if (changeHandler) {
    changeHandler(editorStateTextString);
  }
};

<LexicalComposer initialConfig={editorConfig}>
  <div className="editor-container">
    <ToolbarPlugin aditionalTools={aditionalTools} />
    <div className="editor-inner">
      <RichTextPlugin
        contentEditable={<ContentEditable className="editor-input" />}
        placeholder={<Placeholder placeholder={placeholder} />}
      />
      <OnChangePlugin ignoreInitialChange onChange={onChange} />
    </div>
  </div>
</LexicalComposer>
1 Answers

You should definitely save the JSON into the database. The most important thing is that this let's you decide how to render it. Maybe in some cases you want to render to HTML, but in others (eg: mobile) you want to render to native elements.

To get the JSON structure you can do:

editor.getEditorState().toJSON();

Also, regarding your second question. Here's how you can get the HTML:

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

...    

const htmlString = $generateHtmlFromNodes(editor, null);

NOTE: you need to call the above method inside the Lexical context (ie: inside a callback like editor.update

Related