Create a Slate Rich Text Editor in React

How to create Editor in React using Slatejs


So far we have seen many Editor Frameworks and their usage guides. Slatejs is a good alternative for Draft-js and it is in beta mode for a long time.

Let’s quickly setup a React project and install the slate dependencies.

npx create-react-app myapp
yarn add slate slate-react

Make sure all the dependencies and peer dependencies properly added.

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

const SlateEditor = () => {
  const editor = useMemo(() => withReact(createEditor()), []);
  const initialValue = [
    {
      type: "paragraph",
      children: [{ text: "A line of text in a paragraph." }]
    }
  ];
  const [value, setValue] = useState(initialValue);

  return (
    <Slate editor={editor} value={value} onChange={setValue}>
      <Editable />
    </Slate>
  );
};

export default SlateEditor;

Open the example in Sandbox.

Author: Manoj

Developer and a self-learner, love to work with Reactjs, Angular, Node, Python and C#.Net

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.