Component API
Chipster
onRemove

onRemove

The onRemove prop is a callback function that is triggered when an item is removed from the Chipster component. This can happen through clicking the remove button, using keyboard navigation, or programmatic removal.

Type Definition

type OnRemoveCallback = (id: string) => void;

Basic Usage

BasicExample.tsx
import { Chipster } from '@micoblanc/chipster'
 
export default function BasicExample() {
  const handleRemove = (id: string) => {
    console.log('Removed item with id:', id)
    // Additional logic here
  }
 
  return (
    <Chipster onRemove={handleRemove}>
      <Chipster.ItemList />
      <Chipster.Input placeholder="Type and press Enter" />
    </Chipster>
  )
}

Advanced Usage with State Management

StateExample.tsx
export default function StateExample() {
  const [items, setItems] = useState<Array<{ id: string, text: string }>>([])
  
  const handleRemove = (id: string) => {
    setItems(prev => prev.filter(item => item.id !== id))
    // You can perform additional actions like API calls
    removeFromDatabase(id)
  }
 
  return (
    <Chipster 
      onRemove={handleRemove}
      defaultValue={items.map(item => item.text)}
    >
      <Chipster.ItemList 
        removeIcon={<XMarkIcon className="h-4 w-4" />}
      />
      <Chipster.Input placeholder="Add item..." />
    </Chipster>
  )
}

With Custom Remove Button

CustomRemoveExample.tsx
export default function CustomRemoveExample() {
  const handleRemove = (id: string) => {
    // Trigger any animations or side effects before removal
    playRemoveAnimation(id)
    // Then handle the actual removal
    handleItemRemoval(id)
  }
 
  return (
    <Chipster onRemove={handleRemove}>
      <Chipster.ItemList 
        removeButtonClassName="!bg-red-500 !text-white !rounded-full"
        removeIcon={<TrashIcon className="h-4 w-4" />}
      />
      <Chipster.Input placeholder="Type here..." />
    </Chipster>
  )
}

Important Notes

  • The onRemove callback is called after the item is removed from Chipster's internal state
  • The callback receives the unique id of the removed item
  • Removal can be triggered by:
    • Clicking the remove button
    • Pressing backspace when input is empty
    • Using keyboard navigation (backspace on highlighted item)
    • Programmatic removal
  • The callback works even when the component is disabled (useful for cleanup)

Common Use Cases

  • Syncing with external state management
  • Making API calls to delete items
  • Triggering removal animations
  • Updating parent component state
  • Cleaning up associated resources
  • Logging removal actions
  • Real-time data synchronization
  • Undo/redo functionality implementation

Keyboard Interaction

The onRemove callback is also triggered when using keyboard navigation:

  • Backspace when input is empty removes the last item
  • Backspace when an item is highlighted removes that item
  • Delete when an item is highlighted removes that item