How to create a real-time Markdown text editor in React

Draft.js is a rich text editor created for React. It creates components dynamically depending on the format of the text. We'll use it in this tutorial; the first step is to install it.

Installation

terminal
npm i --save draft-js

Apart from this package, we'll need to install draft-js-plugins-editor. This library allows installing plugins on top of Draft.js.

terminal
npm i --save draft-js-plugins-editor

Finally, we'll need to install draft-js-md-keyboard-plugin, which transforms Markdown into rich format text.

terminal
npm i --save draft-js-md-keyboard-plugin

Creating the component

Now we are ready to create the component.

javascript
import React, { useContext, useEffect, useState }     from 'react';
import { EditorState }                                from 'draft-js';
import Editor                                         from 'draft-js-plugins-editor';
import createMarkdownShortcutsPlugin                  from 'draft-js-md-keyboard-plugin';
import 'draft-js/dist/Draft.css';

const MdEditor = () => {

    const [editorState, setEditorState]  = useState(EditorState.createEmpty());
    const mdPlugin                       = [createMarkdownShortcutsPlugin()];
    
    return (
        <Editor
            editorState = { editorState }
            onChange    = { (editorState) => setEditorState(editorState) }
            placeholder = 'Type here Markdown text...'
            plugins     = { mdPlugin }
        />
    );


}

export default MdEditor;

That's it. Now you have a component that allows you to preview Markdown content in real-time. If you want to know how to store the data into a database, check this post.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.