cmdk icon indicating copy to clipboard operation
cmdk copied to clipboard

Can cmdk be used as an Autocomplete/datalist component?

Open moroshko opened this issue 11 months ago • 3 comments

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!

moroshko avatar Mar 14 '24 03:03 moroshko

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

pacocoursey avatar Mar 14 '24 07:03 pacocoursey

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

arturomtm avatar Mar 14 '24 18:03 arturomtm

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.

pacocoursey avatar Mar 14 '24 21:03 pacocoursey