Search code examples
javascriptreactjsnext.jstailwind-cssshadcnui

Input loses focus when Popover opens in ShadCN


This component contains Popover & Input from shadcn. The issue I'm facing is that when I click on the Input to open the Popover, the Input loses focus, and the cursor moves out.

Expected behavior:
When clicking on the Input component, the Popover should open, and the Input should remain focused with the cursor inside it, allowing the user to type without any additional clicks.

Link to Sandbox

"use client";

import { Input } from "@/components/ui/input";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";

export default function Searchbar() {
  return (
    <div className="w-1/3">
      <Popover>
        <PopoverTrigger>
          <Input />
        </PopoverTrigger>
        <PopoverContent>Place content for the popover here.</PopoverContent>
      </Popover>
    </div>
  );
}

Solution

  • You can fix this like so:

    <Popover>
      <PopoverTrigger>
        <Input />
      </PopoverTrigger>
      <PopoverContent onOpenAutoFocus={(e) => e.preventDefault()}>
        Place content for the popover here.
      </PopoverContent>
    </Popover>
    

    Shadcn's <Popover /> uses Radix UI under the hood. The Radix docs for <Popover /> tell you how to prevent the popover from being focused, but it's not apparent. You have to hover the little "i" icon next to onOpenAutoFocus to see that you need to call preventDefault on the event. In my opinion, a section in their docs dedicated to this would be more helpful than hiding it behind a tooltip.

    Here is a working example.