reactjslexicaljs

Lexical React Get Markdown Value


I'm newbie. I want to get markdown value from lexical/react editor. I am using RichTextPlugin in my project. But I can't get value as markdown. How can I get markdown value? Here is my code;


function Placeholder() {
    return <div className="editor-placeholder">Yazmaya başlayabilirsiniz...</div>;
}

const editorConfig = {
    // The editor theme
    namespace: "ArticleEditor",
    theme: ExampleTheme,
    // Handling of errors during update
    onError(error) {
        throw error;
    },
    // Any custom nodes go here
    nodes: [
        HeadingNode,
        ListNode,
        ListItemNode,
        QuoteNode,
        CodeNode,
        CodeHighlightNode,
        TableNode,
        TableCellNode,
        TableRowNode,
        AutoLinkNode,
        LinkNode
    ]
};


export default function Editor() {
    const onChange = (editorState) => {
        editorState.read(() => {
            // Read the contents of the EditorState here.
            const root = $getRoot();
            const selection = $getSelection();
        });
    }
    return (
        <LexicalComposer initialConfig={editorConfig}>
            <div className="editor-container border rounded-2">
                <div className="overflow-auto bg-100 position-relative">
                    <ToolbarPlugin/>
                </div>
                <div className="editor-inner border-top border-dashed">
                    <RichTextPlugin
                        contentEditable={<ContentEditable className="editor-input"/>}
                        placeholder={<Placeholder/>}
                        ErrorBoundary={LexicalErrorBoundary}
                    />
                    <OnChangePlugin onChange={onChange}/>
                    <HistoryPlugin/>
                    {/*<TreeViewPlugin/>*/}
                    {/*<AutoFocusPlugin/>*/}
                    <CodeHighlightPlugin/>
                    <ListPlugin/>
                    <LinkPlugin/>
                    <AutoLinkPlugin/>
                    <TablePlugin/>
                    <ListMaxIndentLevelPlugin maxDepth={7}/>
                    <MarkdownShortcutPlugin transformers={TRANSFORMERS}/>
                </div>
            </div>
        </LexicalComposer>
    );
}

I can get the value as plain text with using $getRoot() in my onChange() function.


Solution

  • According to the lexical documentation, you can convert your editor's nodes into markdown by using the markdown package: https://lexical.dev/docs/packages/lexical-markdown

    import {
      $convertToMarkdownString,
      TRANSFORMERS,
    } from '@lexical/markdown';
    
    const onChange = (editorState) => {
        editorState.read(() => {
            const markdown = $convertToMarkdownString(TRANSFORMERS);
            console.log(markdown);
        });
    }