Search code examples
next.js

How to create search in ui/shadcn?


I try to use this https://ui.shadcn.com/docs/components/command for searching functionality but the problem is that it doesn't overlap the text. enter image description here

as you can see in the image. The dropdown doesn't overlap the test here text. I just want to create a dropdown list when I search for a value. I'm checking the documentation. It doesn't have an option. I'm not sure if this is applicable to this library.

I'm new on this library ui.shadcn


Solution

  • Future reference, you might want to include some code; it's kind of hard to spot an issue this way.

    I had no issue implementing this with the CommandSearch.tsx looking like this:

    interface ICommandProps {
      commands: { value: string; label: string }[];
    }
    
    export default function CommandSearch({ commands }: ICommandProps) {
      const [open, setOpen] = React.useState(false);
      const [inputValue, setInputValue] = React.useState("");
    
      const handleValueChange = (value: string) => {
        setInputValue(value);
        setOpen(!!value);
      };
    
      const filteredCommands = Array.isArray(commands)
        ? commands.filter((command) =>
            command.label.toLowerCase().includes(inputValue.toLowerCase())
          )
        : [];
      console.log("filteredCommands", filteredCommands);
      return (
        <Command className="rounded-lg border shadow-md">
          <CommandInput
            placeholder="Type a command or search..."
            onValueChange={handleValueChange}
          />
          {
            <CommandList>
              {open &&
                filteredCommands.length > 0 &&
                filteredCommands.map((command) => (
                  <CommandItem key={command.value} value={command.value}>
                    {command.label}
                  </CommandItem>
                ))}
            </CommandList>
          }
        </Command>
      );
    }
    }
    

    And the next page looking like this:

    export default function Page() {
      const commands = [
        { value: "calendar", label: "Calendar" },
        { value: "search-emoji", label: "Search Emoji" },
        { value: "calculator", label: "Calculator" },
      ];
    
      return <CommandSearch commands={commands} />;
    }