Skip to content
Shaken UI
Sign in

Input Group

Save

A text field with icons, fixed text, small buttons, and key hints inside its border, labeled like Input.

Category
Forms
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Input Group preview
⌘K
https://
.shaken.dev

Lowercase letters, numbers, and dashes.

$
USD

Set a limit of at least $10.

Checking availability…

Installation

npx @shakenui/cli add input-group

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add input-group --dry-run

Usage

input-group-example.tsx
"use client";

import { useState } from "react";
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, InputGroupKbd } from "@/components/shaken/ui/input-group";

function SearchIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
      <circle cx="7" cy="7" r="4.25" />
      <path d="M10.25 10.25L13.5 13.5" />
    </svg>
  );
}

function CopyIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round">
      <rect x="5.25" y="5.25" width="8" height="8" rx="1.5" />
      <path d="M10.75 5.25V4.25a1.5 1.5 0 0 0-1.5-1.5h-5a1.5 1.5 0 0 0-1.5 1.5v5a1.5 1.5 0 0 0 1.5 1.5h1" />
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3.75 8.25l2.75 2.75 5.75-6" />
    </svg>
  );
}

export default function InputGroupExample() {
  const [copied, setCopied] = useState(false);
  const webhook = "https://hooks.northwind.dev/runs/7f3a9c";

  function copy() {
    void navigator.clipboard?.writeText(webhook);
    setCopied(true);
    window.setTimeout(() => setCopied(false), 1600);
  }

  return (
    <div className="grid w-full max-w-sm gap-5">
      <InputGroup>
        <InputGroupAddon>
          <SearchIcon />
        </InputGroupAddon>
        <InputGroupInput aria-label="Search runs" placeholder="Search runs, tools, and traces" />
        <InputGroupAddon align="end">
          <InputGroupKbd>⌘K</InputGroupKbd>
        </InputGroupAddon>
      </InputGroup>

      <InputGroup label="Workspace URL" description="Lowercase letters, numbers, and dashes.">
        <InputGroupAddon bordered>https://</InputGroupAddon>
        <InputGroupInput defaultValue="northwind" spellCheck={false} />
        <InputGroupAddon align="end">.shaken.dev</InputGroupAddon>
      </InputGroup>

      <InputGroup label="Webhook URL">
        <InputGroupInput readOnly value={webhook} className="font-mono text-xs" />
        <InputGroupAddon align="end">
          <InputGroupButton onClick={copy}>
            {copied ? <CheckIcon /> : <CopyIcon />}
            {copied ? "Copied" : "Copy"}
          </InputGroupButton>
        </InputGroupAddon>
      </InputGroup>

      <InputGroup label="Monthly spend limit" error="Set a limit of at least $10.">
        <InputGroupAddon>$</InputGroupAddon>
        <InputGroupInput inputMode="decimal" defaultValue="5" className="tabular-nums" />
        <InputGroupAddon align="end">USD</InputGroupAddon>
      </InputGroup>

      <InputGroup label="Slug" description="Checking availability…" busy>
        <InputGroupInput defaultValue="release-notes-writer" spellCheck={false} />
      </InputGroup>
    </div>
  );
}

API

PropTypeDefaultDescription
label / description / errorReactNode—InputGroup: a bound label, helper text, and an error that marks the field invalid.
busybooleanfalseInputGroup: a spinner at the end and aria-busy.
align"start" | "end""start"InputGroupAddon: which side the addon sits on; place it before or after the input to match.
borderedbooleanfalseInputGroupAddon: a hairline between the addon and the input.
variant"ghost" | "secondary""ghost"InputGroupButton: visual style.
iconOnlybooleanfalseInputGroupButton: a square 28px button; give it an aria-label.

Accessibility

  • The label is a native <label> bound to InputGroupInput; helper and error text are linked with aria-describedby.
  • Errors set aria-invalid on the input and turn the border red.
  • Clicking empty space in an addon focuses the input, so the whole field is a click target.
  • Buttons inside are real buttons with their own focus ring; the field ring only shows while the input has focus.
  • The busy spinner is decorative and stops rotating under reduced motion; the field sets aria-busy.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/input-group.tsxinput-group
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/input-group/0.1.0.json.

ui/input-group.tsxShow
ui/input-group.tsx
"use client";

import { Input as BaseInput } from "@base-ui/react/input";
import { type ComponentProps, createContext, type MouseEvent, type ReactNode, useContext, useId } from "react";

type ClassName<State> = string | ((state: State) => string | undefined) | undefined;

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

/** Prepends base classes while keeping Base UI's state-function form of className working. */
function withBase<State>(base: string, className: ClassName<State>) {
  return typeof className === "function" ? (state: State) => cx(base, className(state)) : cx(base, className);
}

interface GroupContextValue {
  inputId: string;
  messageId?: string;
  invalid: boolean;
}

const GroupContext = createContext<GroupContextValue | null>(null);

export interface InputGroupProps extends ComponentProps<"div"> {
  /** Visible label, bound to the InputGroupInput inside. */
  label?: ReactNode;
  /** Helper text below the field. */
  description?: ReactNode;
  /** Error message. Marks the field invalid and replaces the description. */
  error?: ReactNode;
  /** Shows a spinner at the end of the field, for example while a value is being checked. */
  busy?: boolean;
  /** Classes for the wrapping element. `className` styles the bordered field. */
  containerClassName?: string;
}

/**
 * A text field with addons inside its border: icons, fixed text such as a protocol or a domain,
 * small buttons, and key hints. It looks and labels like Input. Put exactly one InputGroupInput
 * inside, with InputGroupAddon before or after it.
 */
export function InputGroup({
  label,
  description,
  error,
  busy = false,
  className,
  containerClassName,
  children,
  ...props
}: InputGroupProps) {
  const inputId = useId();
  const messageId = `${inputId}-message`;
  const invalid = error != null && error !== false;
  const message = invalid ? error : description;

  return (
    <GroupContext.Provider value={{ inputId, messageId: message ? messageId : undefined, invalid }}>
      <div className={cx("grid gap-1.5", containerClassName)}>
        {label ? (
          <label htmlFor={inputId} className="text-sm leading-5 font-medium text-zinc-950 dark:text-white">
            {label}
          </label>
        ) : null}
        <div
          data-invalid={invalid || undefined}
          aria-busy={busy || undefined}
          className={cx(
            "flex h-9 w-full min-w-0 items-stretch rounded-lg border bg-white text-sm text-zinc-900 shadow-sm",
            "transition-[border-color,box-shadow] duration-150 ease-out motion-reduce:transition-none",
            "dark:bg-zinc-950 dark:text-zinc-100",
            invalid
              ? "border-red-400 has-[input:focus]:border-red-500 has-[input:focus]:ring-3 has-[input:focus]:ring-red-500/20 dark:border-red-500/60"
              : "border-zinc-300 has-[input:focus]:border-sky-500 has-[input:focus]:ring-3 has-[input:focus]:ring-sky-500/20 dark:border-zinc-700",
            "has-[input:disabled]:cursor-not-allowed has-[input:disabled]:bg-zinc-50 has-[input:disabled]:opacity-60 dark:has-[input:disabled]:bg-zinc-900",
            className,
          )}
          {...props}
        >
          {children}
          {busy ? (
            <span aria-hidden="true" className="flex items-center pr-3">
              <svg viewBox="0 0 16 16" fill="none" className="size-4 text-zinc-400 motion-safe:animate-spin dark:text-zinc-500">
                <circle cx="8" cy="8" r="6" stroke="currentColor" strokeOpacity="0.3" strokeWidth="1.5" />
                <path d="M14 8a6 6 0 0 0-6-6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
              </svg>
            </span>
          ) : null}
        </div>
        {message ? (
          <p id={messageId} className={invalid ? "text-sm text-red-600 dark:text-red-400" : "text-sm text-zinc-500 dark:text-zinc-400"}>
            {message}
          </p>
        ) : null}
      </div>
    </GroupContext.Provider>
  );
}

/**
 * The text input inside an InputGroup. It takes the group's label, description, and error
 * automatically, and inside a Field it registers with the field instead.
 */
export function InputGroupInput({ id, className, "aria-describedby": describedBy, ...props }: BaseInput.Props) {
  const group = useContext(GroupContext);
  return (
    <BaseInput
      id={id ?? group?.inputId}
      aria-invalid={group?.invalid || undefined}
      aria-describedby={cx(group?.messageId, describedBy) || undefined}
      className={withBase(
        cx(
          "h-full w-full min-w-0 flex-1 bg-transparent px-3 text-sm outline-none placeholder:text-zinc-400 dark:placeholder:text-zinc-500",
          "disabled:cursor-not-allowed",
          // Tighten the padding next to an addon so the text sits close to its icon or prefix.
          "[[data-align=start]+&]:pl-2 [[data-align=start][data-bordered]+&]:pl-3 has-[+[data-align=end]]:pr-2",
        ),
        className,
      )}
      {...props}
    />
  );
}

export interface InputGroupAddonProps extends ComponentProps<"div"> {
  /** Which side of the input the addon sits on. Place it before or after the input to match. */
  align?: "start" | "end";
  /** Draws a hairline between the addon and the input, for fixed text such as `https://`. */
  bordered?: boolean;
}

/**
 * An icon, fixed text, button, or key hint at one end of the field. Render a `start` addon
 * before the input and an `end` addon after it. Clicking empty space in it focuses the input.
 */
export function InputGroupAddon({ align = "start", bordered = false, className, onMouseDown, ...props }: InputGroupAddonProps) {
  const group = useContext(GroupContext);

  function handleMouseDown(event: MouseEvent<HTMLDivElement>) {
    onMouseDown?.(event);
    if (event.defaultPrevented || (event.target as HTMLElement).closest("button, a, input, select, textarea")) return;
    const input = group ? document.getElementById(group.inputId) : null;
    if (input) {
      event.preventDefault();
      input.focus();
    }
  }

  return (
    <div
      data-align={align}
      data-bordered={bordered || undefined}
      onMouseDown={handleMouseDown}
      className={cx(
        "flex shrink-0 cursor-text items-center gap-1.5 text-sm whitespace-nowrap text-zinc-500 select-none dark:text-zinc-500",
        "[&_svg]:size-4 [&_svg]:shrink-0 [&_svg]:text-zinc-400 dark:[&_svg]:text-zinc-500",
        align === "start" ? "pl-3" : "has-[button]:pr-1 not-has-[button]:pr-3",
        bordered && (align === "start" ? "border-r border-zinc-950/[0.07] pr-3 dark:border-white/[0.08]" : "border-l border-zinc-950/[0.07] pl-3 dark:border-white/[0.08]"),
        className,
      )}
      {...props}
    />
  );
}

const buttonVariants = {
  ghost: "text-zinc-600 hover:bg-zinc-950/[0.05] hover:text-zinc-950 dark:text-zinc-400 dark:hover:bg-white/[0.08] dark:hover:text-white",
  secondary: cx(
    "border border-zinc-950/12 bg-white text-zinc-950 hover:border-zinc-950/20 hover:bg-zinc-950/[0.03]",
    "dark:border-white/15 dark:bg-black dark:text-white dark:hover:border-white/25 dark:hover:bg-white/[0.06]",
  ),
} as const;

export interface InputGroupButtonProps extends ComponentProps<"button"> {
  variant?: keyof typeof buttonVariants;
  /** A square 28px button for a single icon. Give it an `aria-label`. */
  iconOnly?: boolean;
}

/** A compact button inside an end addon, such as Copy, Reveal, or Search. */
export function InputGroupButton({ variant = "ghost", iconOnly = false, type = "button", className, ...props }: InputGroupButtonProps) {
  return (
    <button
      type={type}
      className={cx(
        "inline-flex h-7 cursor-pointer items-center justify-center gap-1.5 rounded-md text-xs font-medium whitespace-nowrap select-none",
        iconOnly ? "w-7" : "px-2",
        buttonVariants[variant],
        "transition-[background-color,border-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none",
        "focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-500",
        "disabled:pointer-events-none disabled:opacity-45 [&_svg]:size-3.5 [&_svg]:text-current",
        className,
      )}
      {...props}
    />
  );
}

/** A keyboard shortcut hint, for example `⌘K` at the end of a search field. */
export function InputGroupKbd({ className, ...props }: ComponentProps<"kbd">) {
  return (
    <kbd
      className={cx(
        "inline-flex h-5 min-w-5 items-center justify-center rounded-[5px] border px-1 font-mono text-[11px] leading-none font-medium text-zinc-500",
        "border-zinc-950/10 shadow-[0_1px_0_rgb(0_0_0/0.04)] dark:border-white/15 dark:text-zinc-400 dark:shadow-none",
        className,
      )}
      {...props}
    />
  );
}