Preamble: Learning this in preparation for writing a blog system, completely writing a Markdown editor, is not particularly necessary in the current environment, so it is just a simple use

Involved in the document

  1. For-editor: A Markdown editor to be used as the editor at the time
  2. React-markdown: Used as the code after displaying the markdown syntax

Dependencies that need to be downloaded

yarn add react-markdown remark-gfm for-editor react-syntax-highlighter
Copy the code

Using the editor

import React from 'react';
import Editor from 'for-editor';

const toolbar = {
    h1: true.// h1
    h2: true.// h2
    h3: true.// h3
    h4: true.// h4
    img: true./ / picture
    link: true./ / links
    code: true./ / code block
    undo: true./ / cancel
    redo: true./ / redo
    save: true./ / save
    preview: true./ / the preview
    expand: true./ / full screen
    subfield: true.// Single and double column mode
}

export default function Index() {
    const [value, setValue] = React.useState(' ');
    
    const handleChange = (v) = > {
        setValue(v);
    }
    
    return (
        <div>
            <Editor
                value={value}
                onChange={handleChange}
                toolbar={toolbar}
            />
        </div>
    );
}
Copy the code

To display

import React from 'react';
import ReactMarkdown from 'react-markdown';
import gfm from 'remark-gfm'; // Use plugins that cannot be parsed directly
/ / highlight
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { dark } from 'react-syntax-highlighter/dist/esm/styles/prism';

// Process some nodes
const components = {
    code({ node, inline, className, children, ... props }) {
        const match = /language-(\w+)/.exec(className || ' ');
        return! inline && match) ? (<SyntaxHighlighter style={dark} language={match[1]} PreTag="div" children={String(children).replace(/\n$/,"')} {. props} / >
        ) : (
            <code className={className} {. props} >
                {children}
            </code>)}}export default function Index() {
    const [value, setValue] = React.useState(' ');
    
    return (
        <div>
            <ReactMarkdown
                components={components}
                remarkPlugins={[gfm]}
                children={value}
            />
        </div>
    );
}
Copy the code