Loading...

Postulate is the best way to take and share notes for classes, research, and other learning.

More info

How to Render Slate-Plugins Nodes as Read-Only HTML/React

Profile picture of Samson ZhangSamson Zhang
Apr 17, 2021Last updated Apr 17, 20212 min read

On Postulate, posts are written in Slate Plugins editor, stored as Slate nodes in the database, and then publicly viewed on a blog page. We obviously don't want to load the entire Slate editor just to display a read-only version of the document on the public page. Instead, we can use the function serializeHTMLFromNodes to take our array of nodes and render them directly to HTML.

We need to give serializeHTMLFromNodes three inputs: an SPEditor, array of plugins, and array of nodes to render. We can simply create an editor with const editor = withReact(createEditorPlugins()); to feed in. The array of plugins is the same as what you fed into your editor.

The function returns an HTML string. To render it in React, we can set an empty div's dangerouslySetInnerHTML to the returned value.

Putting it all together:

const editor = withReact(createEditorPlugins()); const plugins = [ createReactPlugin(), createHistoryPlugin(), ...createBasicElementPlugins(), ...createBasicMarkPlugins(), createAutoformatPlugin(optionsAutoformat), createResetNodePlugin(optionsResetBlockTypePlugin), createSoftBreakPlugin(optionsSoftBreakPlugin), createExitBreakPlugin(optionsExitBreakPlugin), createDeserializeMDPlugin(), ... ]; const nodes = [{"type":"p","children":[{"text":"I collected 25 bananas. I used "},{"bold":true,"text":"Google Maps"},{"text":" to help navigate, and increased my banana-collecting efficiency by 40%."}],"id":1},{"type":"p","children":[{"text":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Eget felis eget nunc lobortis mattis aliquam faucibus. Quam id leo in vitae. Ut morbi tincidunt augue interdum velit euismod. Quisque egestas diam in arcu cursus euismod. Rutrum tellus pellentesque eu tincidunt tortor aliquam null a facilisi cras. In hac habitasse platea dictumst vestibulum rhoncus est pellentesque. Metus aliquam eleifend mi in nulla posuere sollicitudin. Donec massa sapien faucibus et molestie ac feugiat. Sociis natoque penatibus et magnis. Vitae aliquet nec ullamcorper sit amet risus. Sollicitudin tempor id eu nisl nunc mi. Eu tincidunt tortor aliquam nulla facilisi. Aliquam sem fringilla ut morbi tincidunt."}],"id":2}]; ... <div dangerouslySetInnerHTML={{__html: serializeHTMLFromNodes(editor, {plugins: plugins, nodes: nodes})}}/>

This is a very basic example, but we see that paragraphs and marks are rendered correctly:




Comments (loading...)

Sign in to comment

Postulate

Founder and dev notes from building Postulate