Select

A select with a search box and grouped options that picks one option or several. Type to filter, move with the arrow keys, press Enter to choose and Escape to close.

Request a quote

Service

Design

Brand identity
Website design
Illustration

Build

Website build
Online shop
Web app

Care

Hosting
Maintenance
Extras

Content

Copywriting
Photography

Growth

Search set-up
Analytics
Newsletter
Most projects start within two weeks.

Options

Screen
Colour

Code

import { useEffect, useId, useRef, useState } from "react";
import "./select.css";

/* A select with a search box and grouped options. With multiple, value is a
   list and the menu stays open while you pick.

   <Select label="Service" groups={[{ label: "Design", options: ["Brand identity"] }]} value={value} onChange={setValue} /> */
export function Select({
  label,
  groups,
  value,
  onChange,
  multiple = false,
  placeholder = "Choose…",
  searchLabel = "Search",
  defaultOpen = false,
}) {
  const id = useId();
  const root = useRef(null);
  const button = useRef(null);
  const search = useRef(null);
  const list = useRef(null);
  const [open, setOpen] = useState(defaultOpen);
  const [words, setWords] = useState("");
  const [active, setActive] = useState(multiple ? null : value);

  const picked = multiple ? value : value ? [value] : [];
  const match = (option) => option.toLowerCase().includes(words.trim().toLowerCase());
  const shown = groups
    .map((group) => ({ ...group, options: group.options.filter(match) }))
    .filter((group) => group.options.length);
  const items = shown.flatMap((group) => group.options);
  const optionId = (option) => id + "-" + option.replace(/[^a-z0-9]+/gi, "-");

  const show = () => {
    setWords("");
    setActive(picked[0] ?? groups[0]?.options[0] ?? null);
    setOpen(true);
  };
  const hide = (refocus) => {
    setOpen(false);
    if (refocus) button.current.focus();
  };
  const choose = (option) => {
    if (multiple) {
      onChange(picked.includes(option) ? picked.filter((other) => other !== option) : [...picked, option]);
      search.current.focus();
    } else {
      onChange(option);
      hide(true);
    }
  };

  /* Focus goes to the search box when the menu opens by hand. */
  const opened = useRef(defaultOpen);
  useEffect(() => {
    if (open && !opened.current) search.current.focus();
    opened.current = open;
  }, [open]);

  /* A press anywhere else closes the menu. */
  useEffect(() => {
    const away = (event) => {
      if (!root.current.contains(event.target)) setOpen(false);
    };
    document.addEventListener("pointerdown", away);
    return () => document.removeEventListener("pointerdown", away);
  }, []);

  /* Keeps the option the keys act on in view. */
  useEffect(() => {
    const option = active && document.getElementById(optionId(active));
    if (!option || !open) return;
    const box = list.current;
    const top = option.offsetTop;
    const bottom = top + option.offsetHeight;
    if (top < box.scrollTop) box.scrollTop = top - 6;
    else if (bottom > box.scrollTop + box.clientHeight) box.scrollTop = bottom - box.clientHeight + 6;
  }, [active, open]);

  const keys = (event) => {
    const at = items.indexOf(active);
    if (event.key === "ArrowDown") {
      event.preventDefault();
      setActive(items[(at + 1) % items.length] ?? null);
    } else if (event.key === "ArrowUp") {
      event.preventDefault();
      setActive(items[(at - 1 + items.length) % items.length] ?? null);
    } else if (event.key === "Enter") {
      event.preventDefault();
      if (items.includes(active)) choose(active);
    } else if (event.key === "Escape") {
      hide(true);
    } else if (event.key === "Tab") {
      hide(false);
    }
  };

  return (
    <div className="dh-select" ref={root} data-open={open ? "" : undefined}>
      <span id={id + "-label"}>{label}</span>
      <button
        type="button"
        ref={button}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-labelledby={id + "-label " + id + "-value"}
        onClick={() => (open ? hide(true) : show())}
      >
        <span id={id + "-value"} data-empty={picked.length ? undefined : ""}>
          {picked.join(", ") || placeholder}
        </span>
        <svg viewBox="0 0 12 12" aria-hidden="true">
          <path d="M3 4.500 6 7.500l3-3" />
        </svg>
      </button>
      <div className="dh-select-menu">
        <label>
          <svg viewBox="0 0 16 16" aria-hidden="true">
            <path d="M7 2a5 5 0 0 1 3.960 8.050l2.750 2.740a.75.75 0 1 1-1.060 1.060l-2.750-2.740A5 5 0 1 1 7 2Zm0 1.500a3.500 3.500 0 1 0 0 7 3.500 3.500 0 0 0 0-7Z" />
          </svg>
          <input
            type="text"
            ref={search}
            role="combobox"
            aria-expanded="true"
            aria-autocomplete="list"
            aria-controls={id + "-list"}
            aria-activedescendant={items.includes(active) ? optionId(active) : undefined}
            aria-label={searchLabel}
            placeholder="Search…"
            autoComplete="off"
            value={words}
            onChange={(event) => {
              setWords(event.target.value);
              const next = groups.flatMap((group) => group.options);
              const typed = event.target.value.trim().toLowerCase();
              setActive(next.find((option) => option.toLowerCase().includes(typed)) ?? null);
            }}
            onKeyDown={keys}
          />
        </label>
        <div
          role="listbox"
          id={id + "-list"}
          ref={list}
          aria-labelledby={id + "-label"}
          aria-multiselectable={multiple || undefined}
        >
          {shown.map((group) => (
            <div role="group" aria-labelledby={optionId(group.label) + "-group"} key={group.label}>
              <p id={optionId(group.label) + "-group"}>{group.label}</p>
              {group.options.map((option) => (
                <div
                  role="option"
                  id={optionId(option)}
                  key={option}
                  aria-selected={picked.includes(option)}
                  data-active={option === active ? "" : undefined}
                  onPointerMove={() => setActive(option)}
                  onClick={() => choose(option)}
                >
                  {option}
                </div>
              ))}
            </div>
          ))}
          {items.length === 0 && <p className="dh-select-empty">No matches</p>}
        </div>
      </div>
    </div>
  );
}

const services = [
  { label: "Design", options: ["Brand identity", "Website design", "Illustration"] },
  { label: "Build", options: ["Website build", "Online shop", "Web app"] },
  { label: "Care", options: ["Hosting", "Maintenance"] },
];

const extras = [
  { label: "Content", options: ["Copywriting", "Photography"] },
  { label: "Growth", options: ["Search set-up", "Analytics", "Newsletter"] },
];

export function Example() {
  const [service, setService] = useState("Website design");
  const [chosen, setChosen] = useState(["Copywriting", "Analytics"]);
  return (
    <section className="dh-select-card">
      <h3>Request a quote</h3>
      <div className="dh-select-row">
        <Select
          label="Service"
          placeholder="Choose a service"
          searchLabel="Search services"
          groups={services}
          value={service}
          onChange={setService}
        />
        <Select
          label="Extras"
          placeholder="Choose extras"
          searchLabel="Search extras"
          groups={extras}
          value={chosen}
          onChange={setChosen}
          multiple
          defaultOpen
        />
      </div>
      <footer>
        <span>Most projects start within two weeks.</span>
        <button type="button">Continue</button>
      </footer>
    </section>
  );
}

Request a quote

Service

Design

Brand identity
Website design
Illustration

Build

Website build
Online shop
Web app

Care

Hosting
Maintenance
Extras

Content

Copywriting
Photography

Growth

Search set-up
Analytics
Newsletter
Most projects start within two weeks.