RendyUI 中文

Components / Select

Select

Text entry · React / TypeScript Free

Recorded demo

Select preview

Source

select.tsx
"use client";

/**
 * Select — replica of the public UI Stacks spec.
 * Original implementation written from the public API docs.
 */
import * as React from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { Check, ChevronDown, Search } from "lucide-react";
import { cn, useControllable, useFocusTrap, useOnClickOutside } from "../internal";

export type SelectOption = {
  value: string;
  label: string;
  description?: string;
  icon?: React.ReactNode;
  disabled?: boolean;
};

export type SelectGroup = {
  label: string;
  options: SelectOption[];
};

export interface SelectProps {
  options: (SelectOption | SelectGroup)[];
  value?: string;
  defaultValue?: string;
  onValueChange?: (value: string) => void;
  placeholder?: string;
  label?: React.ReactNode;
  hint?: React.ReactNode;
  error?: React.ReactNode;
  validation?: "none" | "error";
  variant?: "outline" | "filled";
  size?: "sm" | "md" | "lg";
  icon?: React.ReactNode;
  name?: string;
  disabled?: boolean;
  className?: string;
}

const SIZES = {
  sm: "h-8 text-[13px] px-2.5",
  md: "h-9 text-[14px] px-3",
  lg: "h-10 text-[15px] px-3.5",
} as const;

function isGroup(option: SelectOption | SelectGroup): option is SelectGroup {
  return "options" in option;
}

/**
 * Select: pick one option from a short list. Groups, descriptions and
 * disabled rows are supported; arrow keys, Home / End and type-ahead work.
 */
export function Select({
  options,
  value,
  defaultValue,
  onValueChange,
  placeholder = "Select…",
  label,
  hint,
  error,
  validation = "none",
  variant = "outline",
  size = "md",
  icon,
  name,
  disabled,
  className,
}: SelectProps) {
  const reduce = useReducedMotion();
  const [open, setOpen] = React.useState(false);
  const [selected, setSelected] = useControllable(value, defaultValue ?? "", onValueChange);
  const [activeIndex, setActiveIndex] = React.useState(0);
  const [typeahead, setTypeahead] = React.useState("");
  const rootRef = React.useRef<HTMLDivElement>(null);
  const listRef = React.useRef<HTMLDivElement>(null);
  const triggerRef = React.useRef<HTMLButtonElement>(null);
  const listId = React.useId();

  const flat = React.useMemo(
    () => (options.flatMap((option) => (isGroup(option) ? option.options : [option])) as SelectOption[]),
    [options],
  );
  const current = flat.find((option) => option.value === selected);

  useOnClickOutside(rootRef, () => setOpen(false), open);
  useFocusTrap(listRef, open, { autoFocus: false });

  React.useEffect(() => {
    if (!open) return;
    const index = flat.findIndex((option) => option.value === selected);
    setActiveIndex(index >= 0 ? index : 0);
  }, [open, flat, selected]);

  React.useEffect(() => {
    if (!open || !typeahead) return;
    const elapsed = Date.now() - (typeahead.length > 1 ? Date.now() : 0);
    const query = typeahead.toLowerCase();
    const index = flat.findIndex((option) => option.label.toLowerCase().startsWith(query));
    if (index >= 0) setActiveIndex(index);
    const timer = window.setTimeout(() => setTypeahead(""), 600);
    return () => window.clearTimeout(timer);
    void elapsed;
  }, [typeahead, open, flat]);

  const pick = (option: SelectOption) => {
    if (option.disabled) return;
    setSelected(option.value);
    setOpen(false);
    triggerRef.current?.focus();
  };

  const onKeyDown = (event: React.KeyboardEvent) => {
    if (!open) {
      if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        setOpen(true);
      }
      return;
    }
    switch (event.key) {
      case "ArrowDown":
        event.preventDefault();
        setActiveIndex((index) => (index + 1) % flat.length);
        break;
      case "ArrowUp":
        event.preventDefault();
        setActiveIndex((index) => (index - 1 + flat.length) % flat.length);
        break;
      case "Home":
        event.preventDefault();
        setActiveIndex(0);
        break;
      case "End":
        event.preventDefault();
        setActiveIndex(flat.length - 1);
        break;
      case "Enter":
      case " ":
        event.preventDefault();
        if (flat[activeIndex]) pick(flat[activeIndex]);
        break;
      case "Escape":
        event.preventDefault();
        setOpen(false);
        triggerRef.current?.focus();
        break;
      case "Tab":
        setOpen(false);
        break;
      default:
        if (event.key.length === 1) setTypeahead((prev) => prev + event.key);
    }
  };

  React.useEffect(() => {
    if (!open) return;
    const node = listRef.current?.querySelector<HTMLElement>(`[data-index="${activeIndex}"]`);
    node?.scrollIntoView({ block: "nearest" });
  }, [open, activeIndex]);

  const hasError = Boolean(error) || validation === "error";

  return (
    <div className={cn("flex flex-col gap-1.5", className)} ref={rootRef}>
      {label ? (
        <span className="text-[13px] font-medium text-fg-muted">{label}</span>
      ) : null}
      <div className="relative">
        <button
          type="button"
          ref={triggerRef}
          disabled={disabled}
          role="combobox"
          aria-expanded={open}
          aria-controls={open ? listId : undefined}
          aria-haspopup="listbox"
          aria-invalid={hasError || undefined}
          onClick={() => setOpen((value) => !value)}
          onKeyDown={onKeyDown}
          className={cn(
            "flex w-full items-center gap-2 rounded-[8px] text-left transition-colors",
            "outline-none focus-visible:ring-2 focus-visible:ring-select/60",
            variant === "outline"
              ? "border border-border bg-surface"
              : "border border-transparent bg-muted",
            hasError && "border-danger",
            disabled && "cursor-not-allowed opacity-50",
            SIZES[size],
          )}
        >
          {icon ? <span className="grid place-items-center text-fg-subtle">{icon}</span> : null}
          <span className={cn("flex-1 truncate", !current && "text-fg-subtle")}>
            {current?.label ?? placeholder}
          </span>
          <ChevronDown className="size-4 shrink-0 text-fg-subtle" aria-hidden />
        </button>
        {name ? <input type="hidden" name={name} value={selected} /> : null}

        <AnimatePresence>
          {open ? (
            <motion.div
              id={listId}
              ref={listRef}
              role="listbox"
              initial={reduce ? false : { opacity: 0, y: -4, scale: 0.98 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={reduce ? undefined : { opacity: 0, y: -4, scale: 0.98 }}
              transition={{ duration: 0.14, ease: [0.2, 0, 0, 1] }}
              className="absolute left-0 top-[calc(100%+4px)] z-50 max-h-72 w-full min-w-[200px] overflow-auto rounded-[10px] bg-surface p-1 shadow-[var(--shadow-overlay)]"
            >
              {options.map((option, optionIndex) =>
                isGroup(option) ? (
                  <div key={`group-${option.label}`} role="group" aria-label={option.label}>
                    <div className="px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-fg-subtle">
                      {option.label}
                    </div>
                    {option.options.map((child) => (
                      <OptionRow
                        key={child.value}
                        option={child}
                        index={flat.indexOf(child)}
                        activeIndex={activeIndex}
                        selected={child.value === selected}
                        onActive={setActiveIndex}
                        onPick={pick}
                        optionIndex={optionIndex}
                      />
                    ))}
                  </div>
                ) : (
                  <OptionRow
                    key={option.value}
                    option={option}
                    index={flat.indexOf(option)}
                    activeIndex={activeIndex}
                    selected={option.value === selected}
                    onActive={setActiveIndex}
                    onPick={pick}
                    optionIndex={optionIndex}
                  />
                ),
              )}
            </motion.div>
          ) : null}
        </AnimatePresence>
      </div>
      {error ? (
        <span role="alert" className="text-[12.5px] text-danger">
          {error}
        </span>
      ) : hint ? (
        <span className="text-[12.5px] text-fg-subtle">{hint}</span>
      ) : null}
    </div>
  );
}

function OptionRow({
  option,
  index,
  activeIndex,
  selected,
  onActive,
  onPick,
}: {
  option: SelectOption;
  index: number;
  activeIndex: number;
  selected: boolean;
  onActive: (index: number) => void;
  onPick: (option: SelectOption) => void;
  optionIndex: number;
}) {
  const active = index === activeIndex;
  return (
    <div
      role="option"
      aria-selected={selected}
      aria-disabled={option.disabled || undefined}
      data-index={index}
      tabIndex={-1}
      onMouseEnter={() => onActive(index)}
      onClick={() => onPick(option)}
      className={cn(
        "flex cursor-pointer items-start gap-2 rounded-[7px] px-2 py-1.5 text-[13px]",
        active && "bg-subtle",
        option.disabled && "cursor-not-allowed opacity-40",
      )}
    >
      {option.icon ? (
        <span className="mt-0.5 grid size-4 shrink-0 place-items-center text-fg-subtle">
          {option.icon}
        </span>
      ) : null}
      <span className="min-w-0 flex-1">
        <span className="block truncate font-medium text-fg">{option.label}</span>
        {option.description ? (
          <span className="block truncate text-[12px] text-fg-subtle">{option.description}</span>
        ) : null}
      </span>
      {selected ? <Check className="mt-0.5 size-4 shrink-0 text-select" aria-hidden /> : null}
    </div>
  );
}

export default Select;
export { Search };

Usage

Add the TSX to your React project and install the required dependencies. Styles use Tailwind CSS and theme tokens。

Package dependencies · lucide-react、motion、react

Shared source · internal.ts

Props

NameTypeDescription
`options``({ value; label; description?; icon?; disabled? } \| { label; options })[]`Options, or groups with a heading.
`value / defaultValue``string`Controlled or initial value.
`onValueChange``(value) => void`Called on pick.
`placeholder / label / hint``string / ReactNode / ReactNode`Field text, matching Input.
`error / validation``ReactNode / "none" \| "error"`A message turns the field red; validation marks it without one.
`variant / size``"outline" \| "filled" / "sm" \| "md" \| "lg"`Heights 32, 36 and 40.
`icon / name / disabled``ReactNode / string / boolean`Leading glyph, hidden form input, disabled.