pacocoursey / cmdk

Fast, unstyled command menu React component.
https://cmdk.paco.me
MIT License
9.03k stars 258 forks source link

Can cmdk be used as an Autocomplete/datalist component? #238

Closed moroshko closed 3 months ago

moroshko commented 3 months ago

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!

pacocoursey commented 3 months ago

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).

arturomtm commented 3 months ago

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).

pacocoursey commented 3 months ago

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.