0.0.3 • Published 5 years ago

react-slate-elements v0.0.3

Weekly downloads
5
License
MIT
Repository
github
Last release
5 years ago

React Slate Elements

react-slate-elements is a set of React components to make your life easier when building your own rich text editor using Slate. Check it out:

demo

View demo 👈

Getting started

Install it as any other package:

yarn add react-slate-elements

Now let's see how to put it into action:

import React, { useState, useCallback } from 'react';
import { Value } from 'slate';
import { Editor } from 'slate-react';
import { EditorSchema, EditorToolbar, Bold } from 'react-slate-elements';

const plugins = [
  Bold.Plugin,
]

const App = () => {
  const [value, setValue] = useState(Value.fromJS(initialValue));
  const [editor, setEditorRef] = useState(null);

  const onChangeValue = ({ value }) => setValue(value);
  const onRenderEditor = useCallback(ref => setEditorRef(ref), []);

  const renderMark = (props, editor, next) => {
    switch (props.mark.type) {
      case Bold.TYPE:
        return Bold.Mark(props);
      default:
        return next();
    }
  }

  return (
    <div style={{ margin: 20 }}>
      <EditorToolbar editor={editor}>
        <Bold.Button />
      </EditorToolbar>

      <Editor
        ref={onRenderEditor}
        schema={EditorSchema}
        value={value}
        onChange={onChangeValue}
        renderMark={renderMark}
        plugins={plugins}
      />
    </div>
  );
}

const initialValue = {
  document: {
    nodes: [
      {
        object: 'block',
        type: 'paragraph',
        nodes: [
          {
            object: 'text',
            text: 'A line of text in a paragraph.',
          },
        ],
      },
    ],
  },
};

export default App;

Although it's an arguably quite simple example, all the main concepts are present here and you'll be able to easily extend it to fulfill all your requirements.

In order to allow a bold mark to be used we've:

  1. Added a condition to verify if it should be applied or not on Slate's renderMark function. We check if the current node has the Bold.TYPE and, if positive, we render the mark accordingly through Bold.Mark(props);
  2. Included the <Bold.Button /> inside our <EditorToolbar editor={editor}>, so we'll have a button to toggle this mark;
  3. Added the Bold.Plugin into our editors' plugin array. Because of this, we can press Cmd+b to toggle our bold mark without having to press the toolbar button.

For a complete example, you can check the code used on the demonstration page.

Available Components

UI

Mark

Blocks

Helpers

Big thanks 👏

All icons used here are part of the MaterialDesign project.

0.0.3

5 years ago

0.0.2

5 years ago

0.0.19

5 years ago

0.0.18

5 years ago

0.0.17

5 years ago

0.0.16

5 years ago

0.0.15

5 years ago

0.0.1

5 years ago