Search field
A search box: a magnifier, the text, and a button that clears it. It reports the text as it changes and again on Enter, shows a spinner while a search runs, and has a place for a shortcut hint. For suggestions under the field use a combobox.
Install
npx shadcn@latest add https://thrumui.dev/r/search-field.jsonAdds components/ui/search-field.tsx. Nothing else in your project changes.
import { SearchField } from "@/components/ui/search-field";Automatically installs icons search and x from the icon set.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
value | string | – | The text, when the parent holds it. Use it with onValueChange. |
defaultValue | string | – | The text at first, when the field holds it itself. |
onValueChange | (value: string) => void | – | Called with the text on every change, including when it is cleared. |
onSearch | (value: string) => void | – | Called with the text when Enter is pressed in the field. |
loading | boolean | Default false | A search is running: the magnifier becomes a spinner and the landmark carries aria-busy. |
shortcut | string | – | A key hint at the end of the empty field, such as /. It is only a hint: binding the key is up to the page. |
clearLabel | string | Default "Clear search" | The name of the clear button. |
size | "sm" | "md" | "lg" | Default "md" | sm is 28 pixels tall, md 32, lg 40. |
disabled | boolean | Default false | Disables the field, dims it and removes the clear button. |
sound | boolean | Default true | Play subtle sounds when submitting a search or clearing the query, if the visitor has sound on. |
className | string | – | Extra classes for the landmark around the field. It fills its container; set a width here. |
...props | ComponentProps<"input"> | – | Every other input attribute and event handler goes to the input: placeholder, name, id, aria-label, onChange, readOnly. |
Motion and sound
Motion
- The spinner turns once a second while loading is set.
- The clear button's background fades in over 150 ms on hover and a press scales it to 97%.
- The clear button and the hint appear and leave at once.
- Reduced motion: the spinner stands still and the fades happen at once.
Sound
- A soft click when a non-empty search is submitted with Enter, and a light tick when the field is cleared.
Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works
Accessibility
- The wrapper has the search role, so it is a landmark a screen reader can jump to. The field inside is a native input of type search.
- Name the field with a label element or an aria-label, as the example does: a placeholder is not a name.
- The clear button is a native button named Clear search, 24 pixels square. It is in the page only while there is text to clear.
- While loading, the landmark carries aria-busy. Say the outcome where the results are, for example in a region with the status role.
- The shortcut hint is hidden from screen readers. When the page binds the key, set aria-keyshortcuts on the field.
- A long query scrolls inside the field. Nothing overflows at 160 pixels wide.
| Keys | Action |
|---|---|
| Tab | Focus the field, then the clear button when there is text. |
| Enter | In the field: report the text through onSearch. |
| Esc | In a field with text: clear it. The focus stays in the field, and a dialog around it stays open. |
| Enter / Space | On the clear button: clear the text and move the focus back to the field. |
Source
"use client";
import { useState, type ComponentProps } from "react";
import { cn } from "@/lib/utils";
import { play } from "@/lib/thrum-sound";
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, type InputGroupSize } from "@/components/ui/input-group";
import { SearchIcon } from "@/components/icons/search";
import { XIcon } from "@/components/icons/x";
export type SearchFieldProps = Omit<ComponentProps<"input">, "type" | "size"> & {
/** `sm` is 28 pixels tall, `md` 32, `lg` 40. */
size?: InputGroupSize;
/** Called with the text on every change, including when it is cleared. */
onValueChange?: (value: string) => void;
/** Called with the text when Enter is pressed in the field. */
onSearch?: (value: string) => void;
/** A search is running: the magnifier becomes a spinner and the field is announced as busy. */
loading?: boolean;
/** A key hint at the end of the empty field, such as "/". It is only a hint: binding the key is up to the page. */
shortcut?: string;
/** The name of the clear button. */
clearLabel?: string;
/** Play subtle sounds when submitting a search or clearing the query, if the visitor has sound on. */
sound?: boolean;
};
/** Empties a field the way typing would, so `onChange`, a form and a parent that holds the value all hear it. */
function clear(input: HTMLInputElement | null | undefined) {
if (!input) return;
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, "");
input.dispatchEvent(new Event("input", { bubbles: true }));
input.focus();
}
/**
* A search box: a magnifier, the text, and a button that clears it. It is a native search input inside a search landmark.
* Name it with a `<label>` or an `aria-label`. Enter reports the text through `onSearch`; Escape clears it.
*/
export function SearchField({ size, onValueChange, onSearch, loading = false, shortcut, clearLabel = "Clear search", sound = true, className, value, defaultValue, disabled, readOnly, onChange, onKeyDown, ...props }: SearchFieldProps) {
// Only whether there is text is kept, and only for a field that holds its own value.
const [typed, setTyped] = useState(() => String(defaultValue ?? "") !== "");
const filled = value !== undefined ? String(value) !== "" : typed;
const clearable = filled && !disabled && !readOnly;
return (
<div data-slot="search-field" role="search" aria-busy={loading || undefined} className={cn("w-full min-w-0", className)}>
<InputGroup size={size}>
<InputGroupAddon>
{loading ? (
<svg viewBox="0 0 24 24" className="animate-spin motion-reduce:animate-none" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" aria-hidden="true">
<path d="M12 3.75a8.25 8.25 0 1 0 8.25 8.25" />
</svg>
) : (
<SearchIcon size={16} />
)}
</InputGroupAddon>
<InputGroupInput
type="search"
enterKeyHint="search"
value={value}
defaultValue={defaultValue}
disabled={disabled}
readOnly={readOnly}
// The browser's own clear cross is hidden: the button after the field does that job in every browser.
className="[&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none"
onChange={(event) => {
setTyped(event.target.value !== "");
onChange?.(event);
onValueChange?.(event.target.value);
}}
onKeyDown={(event) => {
onKeyDown?.(event);
// Enter that confirms a word in an input method is not a search.
if (event.defaultPrevented || event.nativeEvent.isComposing) return;
if (event.key === "Enter") {
if (sound && event.currentTarget.value.trim() !== "") play("select");
onSearch?.(event.currentTarget.value);
} else if (event.key === "Escape" && clearable) {
// This Escape is used up: a dialog around the field stays open.
event.preventDefault();
event.stopPropagation();
if (sound) play("tick");
clear(event.currentTarget);
}
}}
{...props}
/>
{clearable ? (
<InputGroupAddon>
<InputGroupButton
aria-label={clearLabel}
sound={false}
onClick={(event) => {
if (sound) play("tick");
clear(event.currentTarget.closest('[data-slot="input-group"]')?.querySelector("input"));
}}
>
<XIcon size={16} />
</InputGroupButton>
</InputGroupAddon>
) : (
shortcut && (
<InputGroupAddon>
<kbd aria-hidden="true" className="rounded-sm border bg-muted px-1.5 font-sans text-xs leading-5 text-muted-foreground">
{shortcut}
</kbd>
</InputGroupAddon>
)
)}
</InputGroup>
</div>
);
}Files and dependencies
- Adds
components/ui/search-field.tsx- Packages
- None
- Brings along
- Input groupSound engine
- Icons
searchx
Changelog
- 1.0.0 · 2026-12-03First release.