Loading...

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

More info

How to Add Custom Blocks in Slate-Plugins

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

When building the editor for Postulate, I wanted a "loading" block to be rendered as images were uploaded. To do this, I implemented a custom block with the "loading" key. Here's how I did it, and how you can do the same for whatever custom block you want.

1. Create the component

First, add a new component to the components object you pass into SlatePlugins. A component is simply a key with a functional React component as its value. Here's what my loading component looks like:

let components = createSlatePluginsComponents(); components["loading"] = props => ( <div style={{padding: "0.5rem", backgroundColor: "#e2e2e2", userSelect: "none"}} contentEditable={false}> <span>Loading...</span> {props.children} </div> );

Make sure you include props.children, even for void blocks, to prevent Slate errors.

2. Create the plugin

Next, add a plugin to the plugins array you pass into SlatePlugins. A plugin is an object with a few properties -- in this case, pluginKeys, renderElement, and voidTypes. Here's the plugin for my loading component:

{ pluginKeys: "loading", renderElement: getRenderElement("loading"), voidTypes: () => ["div"], }

pluginKeys is the key of your block, what node types will be set to. renderElement simply uses the getRenderElement function used by all of Slate Plugins' built-in plugins. voidTypes wants a function that returns an array of type strings; in this case I simply return ["div"].

3. Use your block!

You can now use insertNodes or other transforms to use your custom block!


Comments (loading...)

Sign in to comment

Postulate

Founder and dev notes from building Postulate