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-js
etc. Here is react-quill
an example.
First you need to install react-quill
the 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 useState
to save the content of the editor, and handleEditorChange
the function is used to handle events when the content of the editor changes.
ReactQuill
As the main body of the rich text editor, the component uses value
and onChange
properties to set and obtain the content of the editor.
modules
Properties are used to configure the rich text editor, where the built-in toolbar is used.
placeholder
Property used to display the placeholder when the editor content is empty.
The component will automatically convert the editor's content into HTML
a format, and the content of the format can editorContent
be 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.