useTagGroup
The problem
You want to build a tag group component in your app that's accessible and offers a great user experience. There is no dedicated ARIA design pattern for this component, but since it's widely used, we compiled the list of specifications and implemented them through a React hook that's compliant with Downshift's principles.
This solution
useTagGroup is a React hook that manages all the stateful logic needed to make the tag group functional and accessible. It returns a set of props that are meant to be called, and their results destructured on the tag group's elements: its container, tag item and tag remove button. These are similar to the props provided by vanilla Downshift to the children render prop.
These props are called getter props, and their return values are destructured as a set of ARIA attributes and event listeners. Together with the action props and state props, they create all the stateful logic needed for the tag group to implement the list of requirements. Every functionality needed should be provided out-of-the-box: item removal and selection, and left/right arrow movement between items, screen reader support etc.
Props used in examples
In the examples below, we use the useTagGroup hook and destructure the getter props and state variables it returns. These are used in the following way:
| Returned prop | Element | Comments |
|---|---|---|
getTagGroupProps | <div> | Call and destructure its returned object on the container element. |
getTagProps | <span> | Call and destructure its returned object on the tag element. |
getTagRemoveProps | <button> | Call and destructure its returned object on the tag remove button element. |
items | State value with the items that are part of the tag group. Tags are created based on its iteration. | |
activeIndex | State value with the index of active tag item. Used below for styling. | |
addItem | Imperative function that adds an item to the group. Below, adding items is possible by clicking on the list items. |
For a complete documentation on all the returned props, hook props and more information check out the GitHub Page.
Basic Usage
A tag group can be created with a simple container, and multiple items in the container. Each item also has a button element child that's used to remove the tag.
CodeSandbox for basic usage example.