Reputation: 1330
I have a posts system and when someone submits a post I am saving the editorState
as a JSON string in a Postgres database.
Then, when I need to show the HTML, I am using a custom hook which loads an auxiliary editor just to obtain the HTML.
Is this the proper way? Looks to me a bit overengineering 🤔
I don't want to load other editor, and render it too just to obtain the HTML.
Any idea of how to improve this or suggestion for a different approach? 😄
The render post component:
export const PostDetails = () => {
const postSlug = useParam("postSlug", "string")
const [postDetails] = useQuery(getPostPageDetails, { slug: postSlug })
const { html, AuxEditor } = useGetHtmlFromState(postDetails.content as unknown as EditorState)
return (
<>
<AuxEditor />
<Text dangerouslySetInnerHTML={{ __html: html }} />
</>
)
}
The hook to get the HTML useGetHtmlFromState (it uses the same config as the input)
export const useGetHtmlFromState = (state: EditorState) => {
const [html, setHtml] = useState("")
function MyCustomStateToHtmlPlugin() {
const [editor] = useLexicalComposerContext()
editor.update(() => {
const html = $generateHtmlFromNodes(editor, null)
setHtml(html)
})
return null
}
const AuxEditor = () => {
return (
<LexicalComposer
initialConfig={{
namespace: "MyEditor",
onError: console.error,
editorState: state,
theme: exampleTheme,
nodes: [
HeadingNode,
ListNode,
ListItemNode,
QuoteNode,
CodeNode,
CodeHighlightNode,
TableNode,
TableCellNode,
TableRowNode,
AutoLinkNode,
LinkNode,
],
}}
>
<MyCustomStateToHtmlPlugin />
</LexicalComposer>
)
}
return { html, AuxEditor }
}
Upvotes: 2
Views: 3751
Reputation: 182
I think what you have is a creative way to turn SerializedEditorState
into HTML. You could experiment with @lexical/headless, but it's essentially the same approach. Alternatively, there are a couple of other ways to solve the underlying problem of displaying saved state.
(1) You can generate the HTML up front and save it to the DB alongside the lexical state. It's a bit duplicative, but it works for the "write once, read many times" use case you've described.
(2) You can use a read-only lexical editor to display the saved state instead of converting it into HTML. You can configure the editor with a different theme if you need more control over the styling of specific elements.
I hope that helps!
Upvotes: 2