Slate

A text-editor framework built with React

yarn add slate slate-react

Concepts

  • Slate is pure JSON objects and any custom properties/actions are up to you, then you can render based on those custom properties

  • Root Editor node, container element nodes, and leaf level text nodes form a tree just like a DOM

  • Paths refer to node, points are a path and offset, and ranges have an anchor(start) and focus(end)

Basic Usage

import React, { useEffect, useMemo, useState } from "react";
import { createEditor } from 'slate';
import { Slate, Editable, withReact } from 'slate-react'

const App = () => {
  // Want editor to be stable across renders 
  const editor = useMemo(() => withReact(createEditor()), []);
  const [value, setValue] = useState([
    {
      type: 'paragraph',
      children: [{ text: 'A line of text in a paragraph.' }],
    },
  ]);

  //create shared Slate context
  return (
    <Slate editor={editor} value={value} onChange={value => setValue(value)}>
      <Editable />
    </Slate>
  )
}

Event Handlers

Custom Blocks

Default internal renderer is just div. Element renderers are just simple React components. Must render children as lowest leaf in component

Use Transforms and events to enter the code block and the renderElement ft to alter it

Custom Formatting

Slate breaks up text into leaves

Executing Commands

Augment editor object to handle your own rich text commands or use plugins, extracting lets you make a toolbar too

Everything put togther above, but using custom commands

Saving to a Database

Just use JSON.stringify/JSON.parse on the value.

Editor

Commands act if user was performing, so happen at cursor

Custom commands

Transforms

Operations

Lower level version of everything that can happen to doc, not extensible

Last updated