Interactive tag cloud above a laptop with React code

Tagging Made Easy: Unleash the Power of React Tag Input

The Orange Cat
The Orange Cat

React Tag Input is a versatile and user-friendly tagging component that seamlessly integrates into your React projects. Inspired by Gmail’s “To” field, this library offers a robust solution for implementing tag input functionality with features like autocomplete, keyboard navigation, and drag-and-drop reordering.

Features

React Tag Input comes packed with a variety of features that make it a powerful choice for developers:

  • Autocomplete: Suggests tags based on a predefined list, enhancing user input speed and accuracy.
  • Keyboard and Mouse Support: Enables efficient tag management through both keyboard shortcuts and mouse interactions.
  • Drag and Drop: Allows users to reorder tags intuitively.
  • Tag Editing: Supports in-place editing of existing tags.
  • Customization: Offers extensive styling options and the ability to create custom components.
  • Clear All Function: Provides an optional button to remove all tags at once.

Installation

To get started with react-tag-input, you’ll need to install the library and its peer dependencies. You can use either npm or yarn for installation.

Using npm:

npm install --save react-tag-input react react-dnd react-dnd-html5-backend react-dom

Using yarn:

yarn add react-tag-input react react-dnd react-dnd-html5-backend react-dom

Make sure you have the following peer dependencies installed with the specified versions:

{
  "react": "^18.2.0",
  "react-dnd": "^14.0.2",
  "react-dnd-html5-backend": "^14.0.0",
  "react-dom": "^18.2.0"
}

Basic Usage

Let’s start with a simple example to demonstrate how to use react-tag-input in your React application.

Setting Up the Component

First, import the necessary modules and create a basic component structure:

import React, { useState } from 'react';
import { WithContext as ReactTags } from 'react-tag-input';
import type { Tag } from 'react-tag-input';

const KeyCodes = {
  comma: 188,
  enter: [10, 13],
};

const App: React.FC = () => {
  const [tags, setTags] = useState<Tag[]>([
    { id: 'Thailand', text: 'Thailand' },
    { id: 'India', text: 'India' },
  ]);

  const handleDelete = (i: number) => {
    setTags(tags.filter((_, index) => index !== i));
  };

  const handleAddition = (tag: Tag) => {
    setTags([...tags, tag]);
  };

  return (
    <div>
      <ReactTags
        tags={tags}
        handleDelete={handleDelete}
        handleAddition={handleAddition}
        delimiters={[KeyCodes.comma, KeyCodes.enter]}
      />
    </div>
  );
};

export default App;

This basic setup creates a component that displays initial tags and allows users to add or delete tags. The handleDelete and handleAddition functions manage the tag state, while the delimiters prop specifies which keys trigger tag creation.

Adding Suggestions

To enhance the user experience, you can add suggestions for tag input:

const suggestions: Tag[] = [
  { id: 'USA', text: 'USA' },
  { id: 'Germany', text: 'Germany' },
  { id: 'Austria', text: 'Austria' },
  { id: 'Costa Rica', text: 'Costa Rica' },
  { id: 'Sri Lanka', text: 'Sri Lanka' },
  { id: 'Thailand', text: 'Thailand' },
];

const App: React.FC = () => {
  // ... previous code

  return (
    <div>
      <ReactTags
        tags={tags}
        suggestions={suggestions}
        handleDelete={handleDelete}
        handleAddition={handleAddition}
        delimiters={[KeyCodes.comma, KeyCodes.enter]}
        minQueryLength={2}
        placeholder="Add a new country"
      />
    </div>
  );
};

In this example, we’ve added a suggestions array and set the minQueryLength to 2, meaning suggestions will appear after the user types at least two characters. The placeholder prop provides a hint for the input field.

Advanced Usage

Now let’s explore some more advanced features of react-tag-input.

Drag and Drop

To enable drag-and-drop functionality for reordering tags:

const App: React.FC = () => {
  // ... previous code

  const handleDrag = (tag: Tag, currPos: number, newPos: number) => {
    const newTags = tags.slice();
    newTags.splice(currPos, 1);
    newTags.splice(newPos, 0, tag);
    setTags(newTags);
  };

  return (
    <div>
      <ReactTags
        tags={tags}
        suggestions={suggestions}
        handleDelete={handleDelete}
        handleAddition={handleAddition}
        handleDrag={handleDrag}
        delimiters={[KeyCodes.comma, KeyCodes.enter]}
      />
    </div>
  );
};

Custom Rendering

You can customize the rendering of suggestions using the renderSuggestion prop:

const App: React.FC = () => {
  // ... previous code

  const renderSuggestion = (suggestion: Tag, query: string) => (
    <div className="custom-suggestion">
      <span>{suggestion.text}</span>
      <small> (id: {suggestion.id})</small>
    </div>
  );

  return (
    <div>
      <ReactTags
        tags={tags}
        suggestions={suggestions}
        handleDelete={handleDelete}
        handleAddition={handleAddition}
        renderSuggestion={renderSuggestion}
      />
    </div>
  );
};

Editable Tags

To allow users to edit existing tags:

const App: React.FC = () => {
  // ... previous code

  const handleTagUpdate = (i: number, newTag: Tag) => {
    const updatedTags = tags.map((tag, index) => {
      if (index === i) {
        return { ...tag, ...newTag };
      }
      return tag;
    });
    setTags(updatedTags);
  };

  return (
    <div>
      <ReactTags
        tags={tags}
        suggestions={suggestions}
        handleDelete={handleDelete}
        handleAddition={handleAddition}
        handleTagUpdate={handleTagUpdate}
        editable={true}
      />
    </div>
  );
};

Clear All Function

To add a “Clear All” button:

const App: React.FC = () => {
  // ... previous code

  const handleClearAll = () => {
    setTags([]);
  };

  return (
    <div>
      <ReactTags
        tags={tags}
        suggestions={suggestions}
        handleDelete={handleDelete}
        handleAddition={handleAddition}
        clearAll={true}
        handleClearAll={handleClearAll}
      />
    </div>
  );
};

Conclusion

React Tag Input is a powerful and flexible library that simplifies the implementation of tagging functionality in React applications. With features like autocomplete, drag-and-drop, and customizable rendering, it provides a rich user experience while remaining easy to integrate and customize.

By leveraging the examples and advanced usage scenarios presented in this guide, you can create sophisticated tagging systems that enhance the interactivity and usability of your React projects. Whether you’re building a content management system, a task organizer, or any application that benefits from categorization, react-tag-input offers the tools you need to create an intuitive and efficient tagging interface.

Remember to explore the library’s documentation for even more customization options and advanced features. Happy tagging!

Comments