question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Question: How to render a saved JSON editor state as static HTML?

See original GitHub issue

Is it possible to save the editor state from JSON.stringify(editorState.toJSON()); and rehydrate it later but as read-only HTML instead displaying an editor? For example, using Lexical as a blog editor and rendering the output as a static post.

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:5
  • Comments:14 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
cplepagecommented, May 17, 2022

@trueadm Ok i’m getting the hang of it!

Here’s a better snippet for the others

function serializeToHtml(editorState) {
    const renderText = (node) => {
        switch (node.getFormat()) {
            case 1: // bold
                return `<strong>${node.getTextContent()}</strong>`;
            case 1 << 1: // italic
                return `<em>${node.getTextContent()}</em>`;
            case 1 << 2: // strikethrough
                return `<s>${node.getTextContent()}</s>`;
            case 1 << 3: // underline
                return `<u>${node.getTextContent()}</u>`;
            case 1 << 4: // code
                return `<code>${node.getTextContent()}</code>`;
            case 1 << 5: // subscript
                return `<sub>${node.getTextContent()}</sub>`;
            case 1 << 6: // superscript
                return `<sup>${node.getTextContent()}</sup>`;
            default:
                return node.getTextContent();
        }
    };

    const renderStyle = (format) => {
        switch (format) {
            case 1: // left
                return `text-align: left;`;
            case 2: // center
                return `text-align: center;`;
            case 3: // right
                return `text-align: right;`;
            case 4: // justify
                return `text-align: justify;`;
            default: // justify
                console.log("unknown text-align", format);
                return ``;
        }
    };

    const renderNode = (node) => {
        switch (node.getType()) {
            case "root":
                return (node as RootNode).getChildren().map((k) => renderNode(k)).join("");
            case "heading":
                const headingNode = (node as HeadingNode);
                return `<${headingNode.getTag()}>${headingNode.getChildren()
                    .map((k) => renderNode(k))
                    .join("")}</${headingNode.getTag()}>`;
            case "list":
                const listNode = (node as ListNode)
                return `<${listNode.getTag()}>${listNode.getChildren()
                    .map((k) => renderNode(k))
                    .join("")}</${listNode.getTag()}>`;
            case "text":
                return renderText(node);
            case "quote":
                const quoteNode = (node as QuoteNode);
                return `<blockquote>${quoteNode.getChildren()
                    .map((k) => renderNode(k))
                    .join("")}</blockquote>`;
            case "paragraph":
                const paragraphNode = (node as ParagraphNode);
                return `<p${
                    paragraphNode.getFormat() ? ` style="${renderStyle(paragraphNode.getFormat())}"` : ``
                }>${paragraphNode.getChildren().map((k) => renderNode(k)).join("")}</p>`;
            case "listitem":
                const listItemNode = (node as ListItemNode)
                return `<li>${listItemNode.getChildren()
                    .map((k) => renderNode(k))
                    .join("")}</li>`;
            case "link":
                const linkNode = (node as LinkNode)
                return `<a href="${linkNode.getURL()}">${linkNode.getChildren()
                    .map((k) => renderNode(k))
                    .join("")}</a>`;
            default:
                console.log("unknown type", node.getType());
                return "";
        }
    };

    return new Promise(resolve => {
        editorState.read(() => {
           resolve(renderNode($getRoot()));
        });
    });
}

// usage
document.getElementById("output").innerHTML = await serializeToHtml(editorState)
1reaction
trueadmcommented, May 4, 2022

This is meant to be with deserialized JSON of editor state. Does that advice still hold true?

I’d use the @lexical/headless package in this case, then you get the best if both worlds

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to render HTML string as real HTML? - Stack Overflow
First install the package by npm i --save react-render-html ... Within the JSX, it had to be picked from the Component's state. Component...
Read more >
Draft-js - Saving data to the server - React Rocket
Draft.js is nice, but how on earth do I save data to the server? ... import React, { Component } from 'react'; import...
Read more >
Server-Side Rendering (SSR) - Vue.js
Before using SSR for your app, the first question you should ask is whether you ... Pre-rendered pages are generated and served as...
Read more >
ReactJS — A quick tutorial to build dynamic JSON based form.
In this article we will quickly build a dynamic form based on json data with events and states. Don't worry about the CSS...
Read more >
JSON Editor TW5 demo — a non-linear personal web notebook
The json-editor can function even without a schema. The form can be dynamically created on the fly. <$jsoneditor jsonOutput="!!emptyschema-json"/>.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found