Implementing a rich text editor in React

Implementing a rich text editor in React

Preface
To implement a rich text editor in React, we can use existing third-party libraries, such as react-quill, draft-jsetc. Here is react-quillan example.

First you need to install react-quillthe library:

npm install react-quill --save

Then introduce and use it in the components that need to use the rich text editor:

import React, {
    
    useState} from "react";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";

function RichTextEditor() {
    
    
  const [editorContent, setEditorContent] = useState("");

  const handleEditorChange = (content, delta, source, editor) => {
    
    
    setEditorContent(content);
  };

  return (
    <div className="rich-text-editor">
      <ReactQuill
        value={
    
    editorContent}
        onChange={
    
    handleEditorChange}
        modules={
    
    {
    
    
          toolbar: [
            [{
    
     header: [1, 2, false] }],
            ["bold", "italic", "underline", "strike", "blockquote"],
            [
              {
    
     list: "ordered" },
              {
    
     list: "bullet" },
              {
    
     indent: "-1" },
              {
    
     indent: "+1" },
            ],
            ["link", "image"],
            ["clean"],
          ],
        }}
        placeholder="请输入内容"
      />
    </div>
  );
}

export default RichTextEditor;

In the above code, use is used useStateto save the content of the editor, and handleEditorChangethe function is used to handle events when the content of the editor changes.

ReactQuillAs the main body of the rich text editor, the component uses valueand onChangeproperties to set and obtain the content of the editor.

modulesProperties are used to configure the rich text editor, where the built-in toolbar is used.

placeholderProperty used to display the placeholder when the editor content is empty.

The component will automatically convert the editor's content into HTMLa format, and the content of the format can editorContentbe obtained through properties HTML.

Additionally, files need to be loaded in the component quill.snow.css, which are the style files that the editor depends on.

Guess you like

Origin blog.csdn.net/NIKKT/article/details/129953914