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
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'));
You can read about props of react-tag-input component in detail here.
Recommendation
Create Searchbar Component in React
How to create charts in ReactJS
Create Popup Component in React
Create Drag and Drop List in React
MultiSelect Components in React
Create AutoComplete or Autosuggest in React
For more React Tutorials Click here, Node.js Tutorials Click here.
If you like this, share this.