Introducing PrimeReact v11-alpha 🎉Discover Now

useChip

Headless hook for building removable chip elements with custom markup.

Apple
AmyAmy Elsner
Removable
basic-demo

Usage#

import { useChip } from '@primereact/headless/chip';
const { rootProps, removeProps, state, close } = useChip({ onRemove: (e) => {} });
 
<>
    {
        state.visible && (
            <div {...rootProps}>
                <span></span>
                <span {...removeProps}></span>
            </div>

useChip tracks whether the chip is visible and gives you wired-up props for the root and the remove button so keyboard and click dismissal work out of the box. See Primitive for a component-based API.

Features#

  • Visibility state — state.visible reflects whether the chip should be rendered
  • Remove-button bindings — removeProps includes click, Enter, and Backspace handlers so the dismiss element is fully wired
  • Imperative close — close(event) dismisses the chip from anywhere, not just the remove button
  • Remove callback — onRemove fires with the original event so you can sync external collections
  • Data-attribute styling — data-scope and data-part on the root for CSS targeting

Working with callbacks#

React to dismissal#

Use onRemove to update the collection that owns the chip when the user dismisses it.

const { rootProps, removeProps, state } = useChip({
    onRemove: (e) => setTags((prev) => prev.filter((t) => t !== tag))
});
 
{
    state.visible && (
        <div {...rootProps}>
            <span>{tag}</span>
            <span {...removeProps}>x</span>
        </div>
    );
}

Guard rendering with state.visible#

state.visible flips to false after close is called. Conditionally render the chip so it unmounts cleanly.

{
    state.visible && <div {...rootProps}>...</div>;
}

Dismiss from outside the chip#

Call close(event) when you need a different trigger — a confirmation dialog, a bulk-clear button, or a keyboard shortcut — to dismiss the chip.

const { close } = useChip({ onRemove: (e) => {} });
 
<button onClick={(e) => close(e)}>Dismiss</button>;

Styling with data attributes#

The root prop object includes data-scope="chip" and data-part="root" for targeted styling.

[data-scope='chip'][data-part='root'] {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.25rem 0.75rem;
    border-radius: 9999px;
}

API#

useChip#

NameTypeDefault
onRemove(event: useChipRemoveEvent) => void—
Callback fired when the chip is removed.

Accessibility#

Tab reaches the close button when present, and Enter or Space removes the chip. See Primitive for full WAI-ARIA compliance details.