-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcombobox.tsx
85 lines (81 loc) · 2.56 KB
/
combobox.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { useMemo, useState } from 'react';
import { CheckIcon } from 'lucide-react';
import {
Combobox,
ComboboxContent,
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
} from '@/registry/combobox';
import { BOOKS } from '@/constants/items';
export const ComboboxDemo = () => {
const [value, setValue] = useState<string | null>(null);
const bookByValue = useMemo(
() => (value && BOOKS.find(book => book.id === value)) || null,
[value]
);
return (
<div className='space-y-4'>
<Combobox
value={value}
onValueChange={setValue}
filterItems={(inputValue, items) =>
items.filter(({ value }) => {
const book = BOOKS.find(book => book.id === value);
return (
!inputValue ||
(book &&
(book.title.toLowerCase().includes(inputValue.toLowerCase()) ||
book.author.toLowerCase().includes(inputValue.toLowerCase())))
);
})
}
>
<ComboboxInput placeholder='Pick a book...' />
<ComboboxContent>
{BOOKS.map(({ id, title, author }) => (
<ComboboxItem
key={id}
value={id}
label={title}
disabled={id === 'book-5'}
className='ps-8'
>
<span className='text-sm text-foreground'>{title}</span>
<span className='text-xs text-muted-foreground'>{author}</span>
{value === id && (
<span className='absolute start-2 top-0 flex h-full items-center justify-center'>
<CheckIcon className='size-4' />
</span>
)}
</ComboboxItem>
))}
<ComboboxEmpty>No results.</ComboboxEmpty>
</ComboboxContent>
</Combobox>
<div className='flex flex-col items-start'>
{bookByValue ? (
<>
<span className='text-sm text-muted-foreground'>
Selected book:
</span>
<span className='font-semibold'>{bookByValue.title}</span>
<span className='mb-4'>by {bookByValue.author}</span>
</>
) : (
<span className='text-sm text-muted-foreground'>
No book selected.
</span>
)}
{value && (
<>
<span className='text-sm text-muted-foreground'>Value:</span>
<span className='rounded-sm bg-muted px-2 py-1.5 font-mono text-muted-foreground'>
{value}
</span>
</>
)}
</div>
</div>
);
};