10min

Installing Slate

Installing Slate

Slate is a monorepo divided up into multiple npm packages, so to install it you do:

Text
|

You'll also need to be sure to install Slate's peer dependencies:

Text
|

Note, if you'd rather use a pre-bundled version of Slate, you can and retrieve the bundled file! Check out the Using the Bundled Source guide for more information.

Once you've installed Slate, you'll need to import it.

Text
|

Before we use those imports, let's start with an empty <App> component:

Text
|

The next step is to create a new Editor object. We want the editor to be stable across renders, so we use the useMemo hook:

Text
|

Of course we haven't rendered anything, so you won't see any changes.

If you are using TypeScript, you will also need to extend the Editor with ReactEditor as per the documentation on TypeScript. The example below also includes the custom types required for the rest of this example.

TypeScript
|

Next we want to create state for value:

Text
|

Next up is to render a <Slate> context provider.

The provider component keeps track of your Slate editor, its plugins, its value, its selection, and any changes that occur. It must be rendered above any <Editable> components. But it can also provide the editor state to other components like toolbars, menus, etc. using the useSlate hook.

Text
|

You can think of the <Slate> component as providing a "controlled" context to every component underneath it.

This is a slightly different mental model than things like <input> or <textarea>, because richtext documents are more complex. You'll often want to include toolbars, or live previews, or other complex components next to your editable content.

By having a shared context, those other components can execute commands, query the editor's state, etc.

Okay, so the next step is to render the <Editable> component itself:

Text
|

The <Editable> component acts like contenteditable. Anywhere you render it will render an editable richtext document for the nearest editor context.

There's only one last step. So far we've been using an empty [] array as the initial value of the editor, so it has no content. Let's fix that by defining an initial value.

The value is just plain JSON. Here's one containing a single paragraph block with some text in it:

Text
|

There you have it!

That's the most basic example of Slate. If you render that onto the page, you should see a paragraph with the text A line of text in a paragraph. And when you type, you should see the text change!

Updated 13 Jul 2021
Did this page help?
Yes
No