0

I'm trying to write a blog for myself for the first time, and I've been using Lexical(facebook/lexical: https://github.com/facebook/lexical) to build a rich text editor in the panel for the past two months. It works great and I was able to store the text with nodes to the database properly. But now I don't know how to display them properly on the front end. I'm not sure if I should use the same editor in read-only mode for rich text with formatting? Or do I need to turn them into HTML nodes for rendering?

There is code sandbox link: https://codesandbox.io/s/ecstatic-sanderson-74ezz4?file=/src/App.tsx

xport const MyEditor = (props: any) => {
    const init = () => {
        return props.content
    }
    const ct = init()
    console.log(props.content)
    const initConfig = {
        namespace: 'MyEditor',
        theme:EditorTheme,
        onError(error: any) {
            throw error;
        },
        editorState: ct,


        \\I guess this switch used for rendering text
        editable: false,

        nodes: [
            HeadingNode,
            ListNode,
            ListItemNode,
            QuoteNode,
            CodeNode,
            CodeHighlightNode,
            TableNode,
            TableCellNode,
            TableRowNode,
            AutoLinkNode,
            LinkNode
        ],
    }


    return (
        <>
            <LexicalComposer initialConfig={initConfig}>
                <RichTextPlugin contentEditable={<ContentEditable />}
                                placeholder={<div>Loading</div>}
                                ErrorBoundary={LexicalErrorBoundary} />
                <HistoryPlugin />
                <AutoFocusPlugin />
                <CodeHighlightPlugin />
                <ListPlugin />
                <LinkPlugin />
                <AutoLinkPlugin />
                <ListMaxIndentLevelPlugin maxDepth={7} />
                <MarkdownShortcutPlugin transformers={TRANSFORMERS} />
            </LexicalComposer>
        </>
    );
}
HappyKoala
  • 191
  • 1
  • 11

1 Answers1

1

Yes, our recommended approach is to use a LexicalEditor instance with the "editable" configuration option set to false. This lets Lexical handle the rendering from JSON -> HTML in the same way that it does in editable mode and saves you the trouble of writing a separate renderer to go from Lexical JSON to HTML.

There may be some advanced use cases where you'd want to change the visual appearance of the content in read mode. In that case, this solution won't work as well for you, but you can use $generateHtmlFromNodes or write you own rendering logic.

ace
  • 180
  • 6