Skip to content
Components

Combobox

Combobox for a useful, keyboard-friendly product interface.

Open ↗

Make it yours.

Install the editable source and its dependencies into your React + Tailwind project.

Scroll horizontally for long lines
pnpm dlx shadcn@4.0.8 add http://localhost:3000/r/combobox.json

Use it

Scroll horizontally for long lines
"use client";
import {Combobox} from '@/components/jez-ui/ui/combobox';

export default function Example(){

return <><div className="w-full max-w-sm"><div className="mb-7"><h3 className="text-2xl tracking-tight">Choose your starting point.</h3><p className="mt-2 text-sm leading-relaxed text-muted-foreground">The right tools for the way you work.</p></div><Combobox options={[{label:'React',value:'react',description:'Build interactive interfaces'},{label:'Next.js',value:'next',description:'React with server rendering'},{label:'Vite',value:'vite',description:'A fast development toolchain'},{label:'Astro',value:'astro',description:'Content-driven websites'},{label:'Remix',value:'remix',description:'Full-stack web applications'}]} label="Choose framework"/></div></>;
}

Props & types

Scroll horizontally for long lines
{
  options: { label: string; value: string; description?: string }[];
  value?: string;
  defaultValue?: string;
  onValueChange?: (value: string) => void;
  label?: string;
  className?: string;
}

Source

View 5 source files

registry/ui/combobox.tsx

Scroll horizontally for long lines
"use client";
import * as React from "react";
import { Check, ChevronsUpDown, Search } from "lucide-react";
import { cn } from "./utils";
import { Popover as P } from "radix-ui";
import { useControllable } from "./use-controllable";
import { Input } from "./input";
import { Button } from "./button";
export function Combobox({
  options,
  value,
  defaultValue = "",
  onValueChange,
  label = "Choose item",
  className,
}: {
  options: { label: string; value: string; description?: string }[];
  value?: string;
  defaultValue?: string;
  onValueChange?: (value: string) => void;
  label?: string;
  className?: string;
}) {
  const [selected, setSelected] = useControllable(
    value,
    defaultValue,
    onValueChange,
  );
  const [open, setOpen] = React.useState(false);
  const [query, setQuery] = React.useState("");
  const [active, setActive] = React.useState(0);
  const id = React.useId();
  const filtered = options.filter((o) =>
    o.label.toLowerCase().includes(query.toLowerCase()),
  );
  React.useEffect(() => {
    if (open)
      document
        .getElementById(`${id}-${active}`)
        ?.scrollIntoView({ block: "nearest" });
  }, [active, open, id]);
  return (
    <P.Root
      open={open}
      onOpenChange={(next) => {
        setOpen(next);
        if (next) {
          setQuery("");
          setActive(
            Math.max(
              0,
              options.findIndex((o) => o.value === selected),
            ),
          );
        }
      }}
    >
      <P.Trigger asChild>
        <Button
          variant="outline"
          className={cn("min-w-48 justify-between", className)}
          aria-label={label}
        >
          {options.find((o) => o.value === selected)?.label ?? label}
          <ChevronsUpDown
            size={15}
            className="ml-4 shrink-0 text-muted-foreground"
          />
        </Button>
      </P.Trigger>
      <P.Portal>
        <P.Content
          align="start"
          collisionPadding={16}
          sideOffset={6}
          className="jez-popover z-50 w-72 max-w-[calc(100vw-32px)] rounded-xl border border-border bg-background p-1.5 text-foreground shadow-xl"
        >
          <div className="relative border-b border-border pb-1.5">
            <Search
              size={16}
              className="absolute left-3 top-3 text-muted-foreground"
            />
            <Input
              placeholder="Search options…"
              className="border-0 bg-transparent pl-9 shadow-none focus-visible:ring-0"
              role="combobox"
              aria-label={`Search ${label}`}
              aria-expanded={open}
              aria-controls={id}
              aria-activedescendant={
                filtered[active] ? `${id}-${active}` : undefined
              }
              value={query}
              onChange={(e) => {
                setQuery(e.target.value);
                setActive(0);
              }}
              onKeyDown={(e) => {
                if (e.key === "ArrowDown") {
                  e.preventDefault();
                  setActive((i) => Math.min(i + 1, filtered.length - 1));
                }
                if (e.key === "ArrowUp") {
                  e.preventDefault();
                  setActive((i) => Math.max(0, i - 1));
                }
                if (e.key === "Home" || e.key === "End") {
                  e.preventDefault();
                  setActive(e.key === "Home" ? 0 : filtered.length - 1);
                }
                if (e.key === "Enter" && filtered[active]) {
                  setSelected(filtered[active].value);
                  setOpen(false);
                }
              }}
            />
          </div>
          <div
            id={id}
            role="listbox"
            aria-label={label}
            className="mt-2 max-h-52 overflow-auto"
          >
            {filtered.map((o, i) => (
              <div
                key={o.value}
                id={`${id}-${i}`}
                role="option"
                aria-selected={selected === o.value}
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => {
                  setSelected(o.value);
                  setOpen(false);
                }}
                className={cn(
                  "flex cursor-pointer items-center gap-3 rounded-md px-3 py-2.5 text-sm",
                  i === active && "bg-muted",
                )}
                onPointerMove={() => setActive(i)}
              >
                <span className="min-w-0 flex-1">
                  <span className="block font-medium">{o.label}</span>
                  {o.description && (
                    <span className="text-xs text-muted-foreground">
                      {o.description}
                    </span>
                  )}
                </span>
                {selected === o.value && <Check size={16} />}
              </div>
            ))}
            {!filtered.length && (
              <p className="p-3 text-sm text-muted-foreground">
                No matching items.
              </p>
            )}
          </div>
        </P.Content>
      </P.Portal>
    </P.Root>
  );
}

registry/ui/utils.ts

Scroll horizontally for long lines
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...values: ClassValue[]) {
  return twMerge(clsx(values));
}

registry/ui/use-controllable.ts

Scroll horizontally for long lines
"use client";
import { useState } from "react";
export function useControllable<T>(
  value: T | undefined,
  initial: T,
  onChange?: (value: T) => void,
) {
  const [local, setLocal] = useState(initial);
  return [
    value === undefined ? local : value,
    (next: T) => {
      if (value === undefined) setLocal(next);
      onChange?.(next);
    },
  ] as const;
}

registry/ui/input.tsx

Scroll horizontally for long lines
"use client";
import * as React from "react";
import { cn } from "./utils";
export function Input({ className, ...props }: React.ComponentProps<"input">) {
  return (
    <input
      className={cn(
        "block h-10 w-full min-w-0 rounded-lg border border-border bg-background px-3 text-sm leading-normal shadow-[0_1px_2px_#00000004] transition-[border-color,box-shadow] placeholder:text-muted-foreground/75 hover:border-foreground/25 focus:border-primary focus:outline-none focus:ring-3 focus:ring-primary/10 aria-invalid:border-danger aria-invalid:ring-danger/10 disabled:cursor-not-allowed disabled:bg-muted/50 disabled:opacity-50",
        className,
      )}
      {...props}
    />
  );
}

registry/ui/button.tsx

Scroll horizontally for long lines
"use client";
import * as React from "react";
import { Slot } from "radix-ui";
import { LoaderCircle } from "lucide-react";
import { cn } from "./utils";
export type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
  variant?: "primary" | "secondary" | "outline" | "ghost" | "danger";
  size?: "sm" | "md" | "lg";
  loading?: boolean;
  asChild?: boolean;
};
export function Button({
  variant = "primary",
  size = "md",
  loading,
  asChild,
  className,
  children,
  disabled,
  ...props
}: ButtonProps) {
  const Comp = asChild ? Slot.Root : "button";
  return (
    <Comp
      type={asChild ? undefined : "button"}
      disabled={asChild ? undefined : disabled || loading}
      aria-disabled={disabled || loading || undefined}
      aria-busy={loading || undefined}
      className={cn(
        "relative inline-flex shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-lg border border-transparent text-sm font-medium leading-none transition-[background-color,border-color,box-shadow,transform] duration-150 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-[.98] disabled:pointer-events-none disabled:opacity-45 aria-disabled:pointer-events-none [&_svg]:shrink-0",
        {
          "bg-primary text-primary-foreground shadow-[inset_0_1px_0_#ffffff26,0_1px_2px_#00000012] hover:bg-primary/90":
            variant === "primary",
          "border-border/60 bg-muted text-foreground hover:bg-muted/70":
            variant === "secondary",
          "border-border bg-background text-foreground shadow-sm hover:bg-muted/60":
            variant === "outline",
          "text-muted-foreground hover:bg-muted hover:text-foreground":
            variant === "ghost",
          "bg-danger text-danger-foreground hover:bg-danger/90":
            variant === "danger",
        },
        {
          "h-8 px-3 text-xs": size === "sm",
          "h-10 px-4": size === "md",
          "h-12 px-6": size === "lg",
        },
        className,
      )}
      {...props}
    >
      {asChild ? (
        children
      ) : (
        <>
          <span
            className={cn(
              "inline-flex min-w-0 flex-1 items-center justify-center gap-2",
              loading && "invisible",
            )}
          >
            {children}
          </span>
          {loading && (
            <LoaderCircle
              aria-hidden="true"
              className="absolute size-4 animate-spin motion-reduce:animate-none"
            />
          )}
        </>
      )}
    </Comp>
  );
}

Dependencies

lucide-react@0.577.0 · radix-ui@1.6.7 · clsx@2.1.1 · tailwind-merge@3.5.0

Accessibility & behaviour

Provide meaningful labels and preserve keyboard focus styles. Check contrast when customising theme colours.

Read the accessibility and performance guide →