useTagGroup
useTagGroup lets people move between tags with the arrow keys and remove them
with the keyboard or a remove button.
Quickstart
import React from 'react'
import {useTagGroup} from 'downshift'
const fruits = ['Apple', 'Apricot', 'Banana']
export default function FruitTags() {
const {items, getTagGroupProps, getTagProps, getTagRemoveProps} = useTagGroup(
{initialItems: fruits},
)
return (
<div {...getTagGroupProps({'aria-label': 'Selected fruit'})}>
{items.map((fruit, index) => (
<span key={fruit} {...getTagProps({index, 'aria-label': fruit})}>
{fruit}
<button
type="button"
{...getTagRemoveProps({index, 'aria-label': 'Remove'})}
>
×
</button>
</span>
))}
</div>
)
}
Tab to the first tag, press Arrow Right to focus Apricot, then press Delete to remove it.
Using object items
The book example uses each title as the tag's label and calls addItem to put a
book back in the group.
Open the book example in CodeSandbox.
Live Editor
Result
Loading...
Props used in examples
| Returned prop | Element | Purpose |
|---|---|---|
getTagGroupProps | <div> | Labels the group and handles keyboard navigation. |
getTagProps | <span> | Makes the tag at index focusable by the hook. |
getTagRemoveProps | <button> | Removes the tag at index. |
items | The items to render as tags. | |
activeIndex | Index of the active tag. | |
addItem | Adds an item to the group. |
See the useTagGroup API reference for all props and return values.