cmdk
cmdk copied to clipboard
Can cmdk be used as an Autocomplete/datalist component?
Looking at the docs, I couldn't figure out whether cmdk
could be used as an Autocomplete (or a datalist
) component or not.
Basically, I'd like to have an input that's always visible in my form. Once the user starts typing, they'll be getting suggestions.
If it is possible, having an example would be great!
Yes, this is possible. I'll revisit with an example, but here's the rough idea:
const [search, setSearch] = React.useState('');
const [focused, setFocused] = React.useState(false);
return (
<Command>
<Command.Input
value={search}
onValueChange={setSearch}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
/>
{focused && search.length > 1 ? (
<Command.List>
{/* ... */}
</Command.List>
) : null}
</Command>
)
You might want to check out the examples from shadcn/combobox
as well (which uses cmdk
under the hood).
I've just done the same solution for a searchable list of items. The 'problem' I've found that way is the list grows/shrinks in height, altering the height of its parent component. Is there a workaround for this, like giving absolute
position to <Command.List>
(tried, but unsuccessfully).
Yes, you can position it however you please. position: absolute
should work just fine. The Cmdk component parts are all unstyled, so you control how they appear on the page.