DEV Community

Cover image for Create tags in React
Chetan Rohilla
Chetan Rohilla

Posted on • Originally published at readymadecode.com

Create tags in React

Tags are the keywords associated to a piece of information. Tags are often used on social websites, email systems, blogs where users can upload their own content. They are separated by comma or enter. Here we will create tags in react applications with the help of react-tag-input component.

Installation

npm install --save react-tag-input
Enter fullscreen mode Exit fullscreen mode

Now, we have <ReactTags /> component which we can use in our class or functional component. Here, we are using this in our App Component.

Create tags in React

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

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

const delimiters = [KeyCodes.comma, KeyCodes.enter];

const App = () => {

  const [tags, setTags] = React.useState([
    { id: 'USA', text: 'USA' },
    { 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);

    setTags(newTags);
  };

  const handleTagClick = index => {
    console.log('The tag at index ' + index + ' was clicked');
  };

  const suggestions = [
      {
        id: 'India',
        text: 'India'
      },
      {
        id: 'USA',
        text: 'USA'
      }
  ];

  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
        />
      </div>
    </div>
  );
};

render(<App />, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

You can read about props of react-tag-input component in detail here.


Please like share subscribe and give positive feedback to motivate me to write more for you.

For more tutorials please visit my website.

Thanks:)
Happy Coding:)

Discussion (0)