Security News
Fluent Assertions Faces Backlash After Abandoning Open Source Licensing
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
react-tag-autocomplete
Advanced tools
A simple, accessible, tagging component ready to drop into your React projects.
React Tag Autocomplete is a simple, accessible, tagging component ready to drop into your React projects. Try the examples here.
Please note: This repository is for version 7 of the component which is under development. To view the current stable version of React Tag Autocomplete see the old repository.
This is a Node.js module available through the npm registry. Node 16 and React 18 or above are required.
Installation is done using the npm install command:
$ npm install -S react-tag-autocomplete@beta
import React, { useCallback, useState } from 'react'
import { ReactTags } from 'react-tag-autocomplete'
import { suggestions } from './country-list'
function CountrySelector() {
const [selected, setSelected] = useState([])
const onAdd = useCallback(
(newTag) => {
setSelected([...selected, newTag])
},
[selected]
)
const onDelete = useCallback(
(tagIndex) => {
setSelected(selected.filter((_, i) => i !== tagIndex))
},
[selected]
)
return (
<ReactTags
labelText="Select countries"
selected={selected}
suggestions={suggestions}
onAdd={onAdd}
onDelete={onDelete}
noOptionsText="No matching countries"
/>
)
}
allowBackspace
allowNew
allowResize
ariaAddedText
ariaDeletedText
ariaDescribedBy
ariaErrorMessage
classNames
closeOnSelect
deleteButtonText
delimiterKeys
id
isDisabled
isInvalid
labelText
newOptionText
noOptionsText
onAdd
onBlur
onCollapse
onDelete
onExpand
onFocus
onInput
onValidate
placeholderText
renderLabel
renderOption
renderTag
selected
startWithFirstOption
suggestions
suggestionsTransform
tagListLabelText
Enable users to delete selected tags when the backspace key is pressed whilst the text input is empty. Defaults to true
.
Enable users to add new (not suggested) tags based on the input text. The new tag label and value will be set as the input text. Defaults to false
.
Enable the text input to automatically resize to fit its value. Defaults to true
.
The status text announced when a selected tag is added. The placeholder %value%
will be replaced by the selected tag label. Defaults to "Added tag %value%"
.
The status text announced when a selected tag is removed. The placeholder %value%
will be replaced by the removed tag label. Defaults to "Removed tag %value%"
.
References elements by ID which contain more information about the component. Defaults to ""
.
References an element by ID which contains more information about errors relating to the component. Defaults to ""
.
Override the default class names used by the component. Defaults to:
{
root: 'react-tags',
rootIsActive: 'is-active',
rootIsDisabled: 'is-disabled',
rootIsInvalid: 'is-invalid',
label: 'react-tags__label',
tagList: 'react-tags__list',
tagListItem: 'react-tags__list-item',
tag: 'react-tags__tag',
tagName: 'react-tags__tag-name',
comboBox: 'react-tags__combobox',
input: 'react-tags__combobox-input',
listBox: 'react-tags__listbox',
noOptions: 'react-tags__listbox-no-options',
option: 'react-tags__listbox-option',
optionIsActive: 'is-active',
}
Controls whether the listbox should be collapsed and active option reset when a tag is selected. Defaults to false
.
The helper text added to each selected tag. The placeholder %value%
will be replaced by the selected tag label. Defaults to "Remove %value% from the list"
.
Array of key names matching KeyboardEvent
key values. When a matching key is pressed it will trigger tag selection. Defaults to ['Enter']
.
The ID attribute given to the component and used as a prefix for all sub-component IDs. This must be unique for each instance of the component. Defaults to: "ReactTags"
.
Disables all interactive elements of the component. Defaults to: false
.
Marks the input as invalid. When true this should be used along with the ariaErrorMessage
prop to provide details about the problem. Defaults to: false
.
The label text used to describe the component and input. Please note that the label is visually hidden with CSS in the example code. Defaults to: "Select tags"
.
The option text shown when the allowNew
prop is enabled. The placeholder %value%
will be replaced by the current input value. Defaults to "Add %value%"
.
The option text shown when there are no matching suggestions. The placeholder %value%
will be replaced by the current input value. Defaults to "No options found for %value%"
.
Callback function called when the user wants to select a tag. Receives the tag. Example:
const [selected, setSelected] = useState([])
function onAdd(newTag) {
setSelected([...selected, newTag])
}
Callback function called when the component loses focus. Receives no arguments.
Callback function called when the listbox collapses. Receives no arguments.
Callback function called when the user wants to remove a selected tag. Receives the index of the selected tag. Example:
const [selected, setSelected] = useState([])
function onDelete(tagIndex) {
setSelected(selected.filter((_, i) => i !== tagIndex))
}
Callback function called when the listbox expands. Receives no arguments.
Callback function called when the component gains focus. Receives no arguments.
Optional callback function called each time the input value changes. Receives the new input value. Example:
const [value, setValue] = useState('')
function onInput(value) {
setValue(value)
}
Callback function called when the input value changes and is used to enable or disable the new option when the allowNew
prop is true. Receives the new input value and should return a boolean. Example:
function onValidate(value) {
return /^[a-z]{4,12}$/i.test(value)
}
The placeholder text shown in the input when it is empty. Defaults to "Add a tag"
.
A custom label component to render. Receives the label text as children, required label element attributes, and classNames
as props. Defaults to null
.
function CustomLabel({ children, classNames, ...labelProps }) {
return (
<div className={classNames.label} {...labelProps}>
{children}
</div>
)
}
A custom option component to render. Receives the pre-rendered text as children, option object, required option element attributes, and classNames
as props. Defaults to null
.
function CustomOption({ children, classNames, option, ...optionProps }) {
const classes = [
classNames.option,
option.active ? 'is-active' : '',
option.selected ? 'is-selected' : '',
]
return (
<div className={classes.join(' ')} {...optionProps}>
{children}
</div>
)
}
A custom selected tag component to render. Receives the selected tag object, required tag element attributes, and classNames
as props. Defaults to null
.
function CustomTag({ classNames, tag, ...tagProps }) {
return (
<button type="button" className={classNames.tag} {...tagProps}>
<span className={classNames.tagName}>{tag.label}</span>
</button>
)
}
An array of selected tags. Each tag is an object which must have a value
and a label
property. Defaults to []
.
const tags = [
{ value: 1, label: 'Apples' },
{ value: 2, label: 'Pears' },
]
For TypeScript users the TagSelected
type can be extended with additional properties:
import type { TagSelected } from 'react-tag-autocomplete'
type CustomTagSelected = TagSelected & { myProperty: string }
const [selected, setSelected] = useState<CustomTagSelected[]>([])
Automatically activate the first option when the listbox is expanded and switch the active option directly from first to last/last to first when the selection wraps. Defaults to false
.
An array of tags for the user select. Each suggestion is an object which must have a value
and a label
property. Suggestions may also specify a disabled
property to make the suggestion non-selectable. Defaults to []
.
const suggestions = [
{ value: 3, label: 'Bananas' },
{ value: 4, label: 'Mangos' },
{ value: 5, label: 'Lemons' },
{ value: 6, label: 'Apricots', disabled: true },
]
For TypeScript users the TagSuggestion
type can be extended with additional properties:
import type { TagSuggestion } from 'react-tag-autocomplete'
type CustomTagSuggestion = TagSuggestion & { myProperty: string }
const suggestions: CustomTagSuggestion[] = []
Callback function to apply a custom filter to the list of suggestions. The callback receives two arguments; the current input value
and the array of suggestions and must return a new array of suggestions. Using this prop you could sort suggestions or change the number of suggestions. Example:
import matchSorter from 'match-sorter'
function suggestionsTransform(value, suggestions) {
return matchSorter(suggestions, value, { keys: ['label'] })
}
The ARIA label text added to the selected tags list. Defaults to "Selected tags"
.
By adding a ref
to any instances of this component you can access its API methods.
const api = useRef(null)
<ReactTags ref={api} />
<button type="button" onClick={() => api.current.input.focus()}>
Focus input
</button>
input.blur(tag)
Removes cursor focus from the input.
input.focus()
Moves cursor focus to the input.
input.value
A getter/setter for the input value. If attempting to set a non-string value it will be stringified.
listBox.collapse()
Collapses the listbox if currently expanded.
listBox.expand()
Expands the listbox if currently collapsed.
listBox.activeOption
A getter for the currently active option.
listBox.isExpanded
A getter for the current listbox state. Returns a suggested option or null
.
It is possible to customize the appearance of the component using CSS, the included styles found in /example/styles.css
are only an example. Custom class names can be provided to the component via the classNames
prop.
This project is written using TypeScript, Prettier for code formatting, ESLint for static analysis, and is tested with Vitest and Testing Library.
This project is ISC licensed. You are free to modify and distribute this code in private or commercial projects but the license and copyright notice must remain.
FAQs
A simple, accessible, tagging component ready to drop into your React projects.
The npm package react-tag-autocomplete receives a total of 31,621 weekly downloads. As such, react-tag-autocomplete popularity was classified as popular.
We found that react-tag-autocomplete demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
Research
Security News
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
Security News
The UK is proposing a bold ban on ransomware payments by public entities to disrupt cybercrime, protect critical services, and lead global cybersecurity efforts.