reactjsgoogle-mapsnext.jsreact-google-autocomplete

google-autocomplete not working with shadcn-ui component `command`


I want to implement Google Place Autocomplete using the shadcn-ui command component in Next.js 13. I was following a tutorial on youtube https://youtu.be/BL2XVTqz9Ek?si=XfnVHs1BRhhL8_Nn. However, in this tutorial, the author uses @reach/combobox, which does not work in Next.js 13

My code using shadcn-ui command component:

return (
    <Command>
      <CommandInput
        value={value}
        onValueChange={(value) => {
          setValue(value);
        }}
        disabled={!ready}
        placeholder="Search an address"
        className="combobox-input"
      />
      <CommandList>
        <CommandGroup>
          {status === "OK" &&
            data.map(({ place_id, description }) => (
              <CommandItem
                key={place_id}
                value={description}
                onSelect={handleSelect}
              />
            ))}
        </CommandGroup>
      </CommandList>
    </Command>
  );
};

result(no autocompletion ): image

git repo given in tutorial:https://github.com/leighhalliday/google-maps-intro

his reach/combobox code :

return (
    <Combobox onSelect={handleSelect}>
      <ComboboxInput
        value={value}
        onChange={(e) => setValue(e.target.value)}
        disabled={!ready}
        className="combobox-input"
        placeholder="Search an address"
      />
      <ComboboxPopover>
        <ComboboxList>
          {status === "OK" &&
            data.map(({ place_id, description }) => (
              <ComboboxOption key={place_id} value={description} />
            ))}
        </ComboboxList>
      </ComboboxPopover>
    </Combobox>
  );

Solution

  • The Mistake

    In the given code:

    <Command>
      <CommandInput
        value={value}
        onValueChange={(value) => {
          setValue(value);
        }} //<---Error
      .....
    </Command>
    

    The mistake lies in the syntax of the onValueChange event handler. Since the Shadcn UI component doesn't use the onChange event handler, you need to set the value prop directly and pass a callback function to onValueChange.

    The Correction

    Corrected code:

    <Command>
      <CommandInput
        value={value}
        onValueChange={setValue}
        // ...
     
    </Command>
    

    output:

    enter image description here Git Repo:https://github.com/Amith-AG/googelapis.git