How to add Tag Input in ReactJS?


We can add a tag input in NextJS by creating a new component for the input field and using the onChange event to handle the inputted tags. We can also use the state to store the tags and display them as they are inputted. Finally, we can add a button or function to submit the final tag list. Let us first understand what is ReactJS and Tag Input.

ReactJS

React is a JavaScript library for building user interfaces. It makes it easy to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render the right components when your data changes. You can also build encapsulated components that manage their own state, then compose them to make complex UIs.

Both small and large, complicated applications can be created with ReactJS. It offers a basic yet reliable feature set to get a web application off the ground. It is easy to master both contemporary and legacy applications and is a faster method of coding a functionality. React provides high quantity of ready-made components readily available.

Tag Input

A tag input is a UI element that allows users to add tags or keywords to an input field. These tags are often used for categorizing or grouping related items, and can be used for search or filtering purposes.

A tag input typically has an input field where users can type in tags, and a button to add the tags to a list. The tags can then be displayed as individual elements, usually with a close button to allow users to remove tags. Some tag inputs also have autocomplete functionality to suggest existing tags as the user types.

To get started first create a new NextJS app and run it on our dev server like this −

npx create-react-app tag-app
cd tag-app
npm start

Approach

  • Install the react-tag-input library by running the following command in your terminal −

npm install react-tag-input
  • Import the library in your component file by adding the following line at the top of the file −

import { TagInput } from 'react-tag-input';
  • Create a state variable to hold the tags, and initialize it with an empty array −

const [tags, setTags] = useState([]);
  • Add the TagInput component to your JSX code and pass in the tags state variable and a callback function for handling tag changes −

<TagInput tags={tags} onChange={(newTags) => setTags(newTags)} />
  • (Optional) You can also customize the TagInput component by passing in additional props such as placeholders and styling. For example, to change the placeholder text for the input field, you can add the following prop −

<TagInput tags={tags} onChange={(newTags) => setTags(newTags)} placeholder="Enter tags here" />
  • Use the tags state variable in your component logic as needed. For example, you can display the tags in a list or use them as input for an API call −

<ul>
   {tags.map((tag) => <li key={tag}>{tag}</li>)}
</ul>

That's it! You now have a functional tag input in your ReactJS project.

Example

import React, { useState } from 'react';
import { render } from 'react-dom';
import { COUNTRIES } from './countries';
import './style.css';
import { WithContext as ReactTags } from 'react-tag-input';
const suggestions = COUNTRIES.map((country) => {
   return {
      id: country,
      text: country,
   };
});
const KeyCodes = {
   comma: 188,
   enter: 13,
};
const delimiters = [KeyCodes.comma, KeyCodes.enter];
const App = () => {
   const [tags, setTags] = React.useState([
      { id: 'Thailand', text: 'Thailand' },
      { id: 'India', text: 'India' },
      { id: 'Vietnam', text: 'Vietnam' },
      { id: 'Turkey', text: 'Turkey' },
   ]);
   const handleDelete = (i) => {
   setTags(tags.filter((tag, index) => index !== i));
};
const handleAddition = (tag) => {
   setTags([...tags, tag]);
};
const handleDrag = (tag, currPos, newPos) => {
   const newTags = tags.slice();
   newTags.splice(currPos, 1);
   newTags.splice(newPos, 0, tag);
   // re-render
   setTags(newTags);
};
const handleTagClick = (index) => {
   console.log('The tag at index ' + index + ' was clicked');
};
return (
   <div className="app">
      <h1> React Tags Example </h1>
         <div>
            <ReactTags
               tags={tags}
               suggestions={suggestions}
               delimiters={delimiters}
               handleDelete={handleDelete}
               handleAddition={handleAddition}
               handleDrag={handleDrag}
               handleTagClick={handleTagClick}
               inputFieldPosition="bottom"
               autocomplete
               editable
            />
         </div>
      </div>
   );
};
render(<App />, document.getElementById('root'));

Output

Updated on: 13-Feb-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements