How to add mentions to draft-js editor using plugin in React
Draft-js is Javascript Editor framework that featured in Facebook and it is an open source project which maintained by Facebook. It has larger user base compared to other. Draft-js was a complete framework for creating Ritch text editors and social interactions.
Plugin
Draft-js Plugins allow us to quickly add features such as tool bars , social mentions.
It is a React Plugin Architecture for Draft.js
Mention Plugin
The mention plugin allow us add mention feature in our editor, one like seen on Facebook, twitter etc. In real world we can fetch mentions from API, in this example we used JS object to store them.
Let’s install create a react project
npx create-react-app dracft-editor
In the project add dependecies as follows
npm install @draft-js-plugins/editor
npm install @draft-js-plugins/mention draft-js
We are ready to build our component. Using the Editor component we can use Editor in our app. The Editor state will manage the state of the app.
Let’s initialize the plugin and pass it as props.
//SimpleMention.tsx
import React, {
ReactElement,
useCallback,
useMemo,
useRef,
useState
} from "react";
import { EditorState } from "draft-js";
import Editor from "@draft-js-plugins/editor";
import createMentionPlugin, {
defaultSuggestionsFilter
} from "@draft-js-plugins/mention";
import editorStyles from "./SimpleMentionEditor.module.css";
import mentions from "./Mentions";
export default function SimpleMentionEditor(): ReactElement {
const ref = useRef<Editor>(null);
const [editorState, setEditorState] = useState(() =>
EditorState.createEmpty()
);
const [open, setOpen] = useState(false);
const [suggestions, setSuggestions] = useState(mentions);
const { MentionSuggestions, plugins } = useMemo(() => {
const mentionPlugin = createMentionPlugin();
// eslint-disable-next-line no-shadow
const { MentionSuggestions } = mentionPlugin;
// eslint-disable-next-line no-shadow
const plugins = [mentionPlugin];
return { plugins, MentionSuggestions };
}, []);
const onOpenChange = useCallback((_open: boolean) => {
setOpen(_open);
}, []);
const onSearchChange = useCallback(({ value }: { value: string }) => {
setSuggestions(defaultSuggestionsFilter(value, mentions));
}, []);
return (
<div
className={editorStyles.editor}
onClick={() => {
ref.current!.focus();
}}
>
<Editor
editorKey={"editor"}
editorState={editorState}
onChange={setEditorState}
plugins={plugins}
ref={ref}
/>
<MentionSuggestions
open={open}
onOpenChange={onOpenChange}
suggestions={suggestions}
onSearchChange={onSearchChange}
onAddMention={() => {
// get the mention object selected
}}
/>
</div>
);
}
Remember you need to add the CSS
import "@draft-js-plugins/mention/lib/plugin.css";
The complete project can be found on Sandbox