Select with clear button
Clearable select
select
🍎 Apples
🍌 Bananas
🥦 Broccoli
🥕 Carrots
🍫 Chocolate
🍇 Grapes
import { useState } from 'react';
import { CloseButton, Combobox, Input, InputBase, useCombobox } from '@mantine/core';
const groceries = [
'🍎 Apples',
'🍌 Bananas',
'🥦 Broccoli',
'🥕 Carrots',
'🍫 Chocolate',
'🍇 Grapes',
];
export function SelectClearable() {
const store = useCombobox({
onDropdownClose: () => store.resetSelectedOption(),
});
const [value, setValue] = useState<string | null>(null);
const options = groceries.map((item) => (
<Combobox.Option value={item} key={item}>
{item}
</Combobox.Option>
));
return (
<Combobox
store={store}
withinPortal={false}
onOptionSubmit={(val) => {
setValue(val);
store.closeDropdown();
}}
>
<Combobox.Target targetType="button">
<InputBase
component="button"
type="button"
aria-label="Pick value"
pointer
rightSection={
value !== null ? (
<CloseButton
size="sm"
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
setValue(null);
store.focusTarget();
}}
aria-label="Clear value"
/>
) : (
<Combobox.Chevron />
)
}
onClick={() => store.toggleDropdown()}
onBlur={() => store.closeDropdown()}
rightSectionPointerEvents={value === null ? 'none' : 'all'}
>
{value || <Input.Placeholder>Pick value</Input.Placeholder>}
</InputBase>
</Combobox.Target>
<Combobox.Dropdown>
<Combobox.Options>{options}</Combobox.Options>
</Combobox.Dropdown>
</Combobox>
);
}