React tags is a fantastically simple tagging component for your React projects
npm install react-tag-input




React-tags is a simple tagging component ready to drop in your projects. The component is inspired by GMail's To field in the compose window.
In Prakhar's words here is why he started it👇🏻
Because I was looking for an excuse to build a standalone component and publish it in the wild? To be honest, I needed a tagging component that provided the above features for my React-Surveyman project. Since I was unable to find one which met my requirements (and the fact that I generally enjoy re-inventing the wheel) this is what I came up with.
Check it out here
```
npm install --save react-tag-input
or via Yarn
`js`
yarn add react-tag-input
make sure you have installed the peer dependencies as well with :point_down: versions
``
"react": "^18.2.0",
"react-dnd": "^14.0.2",
"react-dnd-html5-backend": "^14.0.0",
"react-dom": "^18.2.0"
and suggestions list. Apart from this, there are multiple events, handlers for which need to be set. For more details, go through the API.
`javascript
import React from 'react';
import { createRoot } from 'react-dom/client';
import { StrictMode } from 'react';
import GitHubCorner from './GithubCorner';
import type { Tag } from '../src/components/SingleTag';
import { WithContext as ReactTags, SEPARATORS } from '../src/index';
;const suggestions = COUNTRIES.map((country) => {
return {
id: country,
text: country,
className: '',
};
});
const KeyCodes = {
comma: 188,
enter: [10, 13],
};
const App = () => {
const [tags, setTags] = React.useState>([
{ id: 'Thailand', text: 'Thailand', className: '' },
{ id: 'India', text: 'India', className: '' },
{ id: 'Vietnam', text: 'Vietnam', className: '' },
{ id: 'Turkey', text: 'Turkey', className: '' },
]);
const handleDelete = (index: number) => {
setTags(tags.filter((_, i) => i !== index));
};
const onTagUpdate = (index: number, newTag: Tag) => {
const updatedTags = [...tags];
updatedTags.splice(index, 1, newTag);
setTags(updatedTags);
};
const handleAddition = (tag: Tag) => {
setTags((prevTags) => {
return [...prevTags, tag];
});
};
const handleDrag = (tag: Tag, currPos: number, newPos: number) => {
const newTags = tags.slice();
newTags.splice(currPos, 1);
newTags.splice(newPos, 0, tag);
// re-render
setTags(newTags);
};
const handleTagClick = (index: number) => {
console.log('The tag at index ' + index + ' was clicked');
};
const onClearAll = () => {
setTags([]);
};
return (
React Tags Example
tags={tags}
suggestions={suggestions}
separators={[SEPARATORS.ENTER, SEPARATORS.COMMA]}
handleDelete={handleDelete}
handleAddition={handleAddition}
handleDrag={handleDrag}
handleTagClick={handleTagClick}
onTagUpdate={onTagUpdate}
inputFieldPosition="bottom"
editable
clearAll
onClearAll={onClearAll}
maxTags={7}
/>
);
};
const domNode = document.getElementById('app')!;
const root = createRoot(domNode);root.render(
);
`A note about
Contexts
One of the dependencies of this component is the react-dnd library. Since the 1.0 version, the original author has changed the API and requires the application using any draggable components to have a top-level backend context. So if you're using this component in an existing Application that uses React-DND you will already have a backend defined, in which case, you should require the component without the context.`javascript
const ReactTags = require('react-tag-input').WithOutContext;
`
Otherwise, you can simply import along with the backend itself (as shown above). If you have ideas to make this API better, I'd love to hear.Options
tags | Array | [] | An array of tags that are displayed as pre-selected.|
|suggestions | Array | [] | An array of suggestions that are used as basis for showing suggestions.
|delimiters | Array | [13, 9] | Specifies which characters keycode should terminate tags input. [Deprecated], use separators instead.
|separators | Array | ["Enter", "Tab"] | Specifies which characters should terminate tags input |
|placeholder | String | Add new tag | The placeholder shown for the input.
|labelField | String | text | Provide an alternative label property for the tags.
|handleAddition | Function | undefined | Function called when the user wants to add a tag (required).
|handleDelete | Function | undefined | Function called when the user wants to delete a tag (required).
|handleDrag | Function | undefined | Function called when the user drags a tag.
|handleFilterSuggestions | Function | undefined | Function called when filtering suggestions.
|handleTagClick | Function | undefined | Function called when the user wants to know which tag was clicked.
|autofocus | Boolean | true | Boolean value to control whether the text-input should be autofocused on mount. [Deprecated], use autoFocus instead.
|autoFocus | Boolean | true | Boolean value to control whether the text-input should be autofocused on mount.
|allowDeleteFromEmptyInput | Boolean | true | Boolean value to control whether tags should be deleted when the 'Delete' key is pressed in an empty Input Box.
|handleInputChange | Function | undefined | Event handler for input onChange.
|handleInputFocus | Function | undefined | Event handler for input onFocus.
|handleInputBlur | Function | undefined | Event handler for input onBlur.
|minQueryLength | Number | 2 | How many characters are needed for suggestions to appear.
|removeComponent | Function | | Function to render custom remove component for the tags.
|autocomplete | Boolean/Number | false | Ensure the first matching suggestion is automatically converted to a tag when a separator key is pressed.[Deprecated] and will be removed in v7.x.x, more info in #949
|readOnly | Boolean | false | Read-only mode without the input box and removeComponent and drag-n-drop features disabled.
|name | String | undefined | The name attribute added to the input.
|id | String | undefined | The id attribute added to the input.
|maxLength | Number | Infinity | The maxLength attribute added to the input.
|inline | Boolean | true | Render input field and selected tags in-line. [Deprecated], use inputFieldPosition instead.
|inputFieldPosition | String | inline | Specify position of input field relative to tags
|allowUnique | Boolean | true | Boolean value to control whether tags should be unqiue.
|allowDragDrop | Boolean | true | Implies whether tags should have drag-n-drop features enabled.
|renderSuggestion | Function | undefined | Render prop for rendering your own suggestions.
| inputProps | Object |{} | The extra attributes which are passed to the input field.
| allowAdditionFromPaste | boolean | true | Implies whether to allow paste action when adding tags.|
| editable | boolean | false| Implies whether the tags should be editable.|
| onTagUpdate | Function | | This callback if present is triggered when tag is edited.|
|clearAll | boolean | false | Implies whether 'clear all' button should be shown.
|onClearAll | Function | | This callback if present is triggered when clear all button is clicked.
| maxTags | number | | The maximum count of tags to be added
| ariaAttrs | Object |{clearAllLabel: "clear all tags"} | An object containing custom ARIA attributes to enhance screen reader support and improve accessibilityStyling
does not come up with any styles. However, it is very easy to customize the look of the component the way you want it. By default, the component provides the following classes with which you can style --
ReactTags__tags
- ReactTags__tagInput
- ReactTags__tagInputField
- ReactTags__selected
- ReactTags__selected ReactTags__tag
- ReactTags__selected ReactTags__remove
- ReactTags__suggestions
- ReactTags__activeSuggestion
- ReactTags__editTagInput
- ReactTags__editTagInputField
- ReactTags__clearAll/example/reactTags.css.If you need to set your own class names on the component, you may pass in
a
classNames prop.`js
classNames={{
tags: 'tagsClass',
tagInput: 'tagInputClass',
tagInputField: 'tagInputFieldClass',
selected: 'selectedClass',
tag: 'tagClass',
remove: 'removeClass',
suggestions: 'suggestionsClass',
activeSuggestion: 'activeSuggestionClass',
editTagInput: 'editTagInputClass',
editTagInputField: 'editTagInputField',
clearAll: 'clearAllClass',
}}
...>
`
Preparing for Migration to v7.x.x
Below are the list of
deprecated props so please stop using it and migrate to the new props as these will be removed in v7.x.x.
You will see a warning for the migration as well in the console.-
delimiters - Please use separators instead, more info in this issue.
- inline - Please use inputFieldPosition instead.
- autofocus - Please use autoFocus instead.Additionally the prop
autocomplete is deprecated and will be removed in v7.x.x. If you have any concerns regarding this, please share your thoughts in this issue.
Support
If you like this library, please support it to contribute to its development :)
Dev
The component is written in ES6 and uses Webpack as its build tool.Set up instructions
Install yarn
`
npm install -g yarn
``
git clone git@github.com:react-tags/react-tags.git
cd react-tags
yarn
yarn precommit
yarn start
`
open http://localhost:8090
Contributing
Got ideas on how to make this better? Open an issue!
Thanks
The autocomplete dropdown is inspired by Lea Verou's awesomeplete library. The Drag and drop functionality is provided by Dan Abramov's insanely useful ReactDND library.Also thanks to the awesome contributors who've made the library far better!
[default-suggestions-filter-logic]: https://github.com/react-tags/react-tags/blob/v4.0.1/lib/ReactTags.js#L83
[includes-polyfill]: https://github.com/mathiasbynens/String.prototype.includes
$3
An array of tags that are displayed as pre-selected. Each tag should have an id property, property for the label, which is specified by the labelField and class for label, which is specified by className.`js
// With default labelField
const tags = [ { id: "1", text: "Apples" } ]// With labelField of
name
const tags = [ { id: "1", name: "Apples" } ]// With className
const tags = [ { id: "1", text: "Apples", className: 'red'} ]
`
$3
An array of suggestions that are used as basis for showing suggestions. These objects should follow the same structure as the tags. So if the labelField is name, the following would work:`js
// With labelField of name
const suggestions = [
{ id: "1", name: "mango" },
{ id: "2", name: "pineapple"},
{ id: "3", name: "orange" },
{ id: "4", name: "pear" }
];`$3
This prop is deprecated and will be removed in 7.x.x. Please use separators instead.
Specifies which characters should terminate tags input. An array of character codes. We export the constant KEYS for convenience.
`js
import { WithContext as ReactTags, KEYS } from 'react-tag-input'; delimiters={[KEYS.TAB, KEYS.SPACE, KEYS.COMMA]}
/>
`$3
Specifies which characters should separate tags. An array of strings. We support the below separators :point_down:-
Enter
- Tab
- Space
- Comma
- SemicolonAnd we export the constant
SEPERATORS for convenience.
`js
import { WithContext as ReactTags, SEPARATORS } from 'react-tag-input';
separators={[SEPARATORS.TAB, SEPARATORS.SPACE, SEPARATORS.COMMA]}
/>
`$3
The placeholder shown for the input.`js
let placeholder = "Add new country"
`
$3
Provide an alternative label property for the tags.`jsx
tags={tags}
suggestions={}
labelField={'name'}
handleDrag={}
/>
`This is useful if your data uses the
text property for something else.$3
Function called when the user wants to add a tag (either a click, a tab press or carriage return)`js
function(tag) {
// add the tag to the tag list
}
`
$3
Function called when the user wants to delete a tag`js
function(i) {
// delete the tag at index i
}
`
$3
If you want tags to be draggable, you need to provide this function.
Function called when the user drags a tag.`js
function(tag, currPos, newPos) {
// remove tag from currPos and add in newPos
}
`$3
To assert control over the suggestions filter, you may contribute a function that is executed whenever a filtered set
of suggestions is expected. By default, the text input value will be matched against each suggestion, and [those that
start with the entered text][default-suggestions-filter-logic] will be included in the filters suggestions list. If you do contribute a custom filter
function, you must return an array of suggestions. Please do not mutate the passed suggestions array.For example, if you prefer to override the default filter behavior and instead match any suggestions that contain
the entered text _anywhere_ in the suggestion, your
handleFilterSuggestions property may look like this:`js
function(textInputValue, possibleSuggestionsArray) {
var lowerCaseQuery = textInputValue.toLowerCase() return possibleSuggestionsArray.filter(function(suggestion) {
return suggestion.toLowerCase().includes(lowerCaseQuery)
})
}
`Note: The above custom filter uses
String.prototype.includes, which was added to JavaScript as part of the ECMAScript 7
specification. If you need to support a browser that does not yet include support for this method, you will need to
either refactor the above filter based on the capabilities of your supported browsers, or import a [polyfill for
String.prototype.includes][includes-polyfill].
$3
Function called when the user wants to know which tag was clicked`js
function(i) {
// use the tag details at index i
}
`$3
Optional boolean param to control whether the text-input should be autofocused on mount.
This prop is deprecated and will be removed in 7.x.x, please use autoFocus instead.`jsx
autofocus={false}
...>
`$3
Optional boolean param to control whether the text-input should be autofocused on mount.`jsx
autoFocus={false}
...>
`$3
Optional boolean param to control whether tags should be deleted when the Backspace key is pressed in an empty Input Box. By default this prop is false. However when input field position is
inline, you will be able to delete the tags by pressing Backspace irrespective of the value of this prop.This prop will likely be removed in future versions.
`js
allowDeleteFromEmptyInput={true}
...>
`
$3
Optional event handler for input onChangeSignature
`js
(value, event) => void
`
The value denotes the target input value to be added and the event is the original event for onChange.`js
handleInputChange={this.handleInputChange}
...>
`
$3
Optional event handler for input onFocus`js
handleInputFocus={this.handleInputFocus}
...>
`Signature
`js
(value, event) => void
`
The value denotes the target input value to be added and the event is the original event for onFocus.$3
Optional event handler for input onBlurSignature
`js
(value, event) => void
`
The value denotes the target input value to be added and the event is the original event for onBlur.`js
handleInputBlur={this.handleInputBlur}
...>
`$3
Minimum number of characters needed for suggestions to appear. Defaults to 2.$3
If you'd like to supply your own tag delete/remove element, create a React component and pass it as a property to ReactTags using the removeComponent option. By default, a simple anchor link with an "x" text node as its only child is rendered, but if you'd like to, say, replace this with a