How to add tagging in Next js using quill-mention?

If you want to add tagging in Next js app you can use our step guide. In this guide, we will guide you on how to implement quill mention react.

Tagging is a valuable feature that allows users to mention or tag other users within a text editor. If you’re working with Next.js and want to implement tagging in your React app using the Quill-Mention library, you’ve come to the right place. In this step-by-step guide, we will show you how to integrate tagging functionality into your Next.js application using the Quill-Mention library.

Before we begin, make sure you have the following installed:

  1. Node.js and npm: Ensure you have Node.js and npm installed on your machine to manage dependencies and run the application.
  2. Next.js project: Set up a basic Next.js project if you haven’t already.

Installing Dependencies

To get started, navigate to your Next.js project directory in the terminal and install the necessary dependencies:

npm i react-quill quill-mention

Implementing the Tagging Editor Component

In your Next.js project, create a new file named Editor.tsx in a suitable folder, and copy the following code into it. Now we will add mention module in the modules object.

import React, { useCallback, useRef } from 'react';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import 'quill-mention';
import 'quill-mention/dist/quill.mention.css';

interface Props {
  atValues?: { id: number; value: string }[] | Record<string, any>;
  onChange?: (value: string) => void;
  height?: string;
  toolbarOptions?: Record<string, any>;
  formatOptions?: string[];
  value?: string;
}

const Editor: React.FC<Props> = function (props: Props) {
  const { atValues, value, onChange, toolbarOptions, formatOptions } = props;
  const reference = useRef(null);

  const modules = {
    mention: {
      allowedChars: /^[A-Za-z\sÅÄÖåäö]*$/,
      mentionDenotationChars: ['@'],
      source: useCallback(
        async (
          searchTerm: string,
          renderItem: (arg0: { id: number; value: string }[] | undefined, arg1: any) => void,
          mentionChar: string,
        ) => {
          let values;

          if (mentionChar === '@') {
            values = atValues;
          }

          if (searchTerm.length === 0) {
            renderItem(values as any, searchTerm);
          } else if (values) {
            const matches = atValues?.filter((item: any) =>
              item.value.toLowerCase().includes(searchTerm.toLowerCase()),
            );
            renderItem(matches, searchTerm);
          }
        },
        [],
      ),
    },

    toolbar: toolbarOptions || [
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      ['bold', 'italic', 'underline', 'strike', 'blockquote'],
      [{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
      ['image', 'code-block', 'link'],
      [{ background: [] }],
      [{ color: [] }],
    ],
  };

  const formats = formatOptions || [
    'header',
    'font',
    'size',
    'bold',
    'italic',
    'underline',
    'strike',
    'blockquote',
    'list',
    'bullet',
    'indent',
    'link',
    'image',
    'code-block',
    'color',
    'background',
  ];

  return (
    <>
      <ReactQuill
        style={{ color: '#0B0E1E' }}
        theme="snow"
        ref={reference}
        modules={modules}
        onChange={onChange}
        formats={formats}
        value={value}
      />
    </>
  );
};

export default React.memo(Editor);

This Editor component wraps the ReactQuill editor and integrates the Quill-Mention library to enable tagging functionality.

Using the Tagging Editor in Your Parent Component

Now that we have our Editor component ready, let’s use it in your parent component. Make sure you have the necessary state and functions to handle the editor’s value changes. Here’s an example of how to implement it:

import React, { useState } from 'react';
import Editor from './Editor'; // Replace './Editor' with the correct path to your Editor component
// ...

const usersList = [{ id: 1, value: 'sufyan' }, { id: 2, value: 'Dev-sufyan' }];

const COMMENT_FORMAT_OPTIONS = [...]; // Define your desired format options
const COMMENT_TOOLBAR_OPTIONS = [...]; // Define your desired toolbar options

const ParentComponent: React.FC = () => {
  const [message, setMessage] = useState('');

  const handleChange = (value: string) => {
    const trimmedValue = value.trim();

    if (trimmedValue === '<p><br></p>') {
      setMessage('');
    } else {
      setMessage(value);
    }
  };

  return (
    <>
      {usersList.length > 0 && (
        <Editor
          onChange={handleChange}
          atValues={usersList}
          formatOptions={COMMENT_FORMAT_OPTIONS}
          toolbarOptions={COMMENT_TOOLBAR_OPTIONS}
          value={message}
        />
      )}
    </>
  );
};

export default ParentComponent;

In this example, we import the Editor component we created earlier and use it in our parent component. We also pass the handleChange function to the Editor as a prop to capture changes made in the editor.

Testing the Tagging Editor

When you run your Next.js application, you should see the tagging-enabled editor. Start typing “@” in the editor, and you should see suggestions based on the usersList provided. You can select a user from the suggestions, and the tag will be added to the editor content.

Congratulations! You have successfully added tagging functionality to your Next.js application using the Quill-Mention library.

One Last thing

Tagging is a powerful feature that enhances user interaction in text editors. By integrating the Quill-Mention library into your Next.js application, you can easily implement tagging and enable users to mention others within your editor. Following this step-by-step guide, you now have the knowledge and code to create a tagging-enabled editor in your Next.js project. Feel free to customize the implementation based on your specific requirements to create a seamless user experience in your application. Happy coding!

Leave a Comment