Menu

Components

Text Field

A field for typing text, with a label, help text and an error message. Built on react-aria-components.

Introduction

Text Field is the everyday input: a name, an email, a password, a short note. It puts a label, the input, help text and an error message together, so every field in a form looks and behaves the same.

  • type for email, password, URL and phone, and isMultiline for longer text.
  • An icon or a short text before and after the input, with prefix and suffix.
  • Password fields get a button to show and hide the text. A character counter is one prop away.
  • Works in a form: give it a name and the text is submitted with it.

Searching? Use Search Field. Choosing from a list? Use Select or Autocomplete.

Installation

centerUI has no CLI or registry yet: components are copied into your project. Text Field uses Button for the password toggle, so it needs everything Button needs.

# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx

# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx

# npm
npm install react-aria-components tailwind-variants tailwind-merge clsx

Add Button first (see its Manual installation), then follow the steps below.

Manual installation

Copy these files into your project and keep the paths, or adjust the imports.

1. Add the styles

src/types/text-field-styles.tsShow code
import { tv } from "tailwind-variants";

// The frame around the prefix, the input and the suffix. It is a plain
// element, not the input itself, so everything sits inside one border and the
// focus ring wraps all of it.
export const textFieldStyles = tv({
  slots: {
    frame: [
      "flex w-full gap-2 rounded-md text-fg transition-colors",
      "focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-bg",
      "group-data-invalid/text-field:border-danger",
      "group-data-disabled/text-field:pointer-events-none group-data-disabled/text-field:opacity-50",
      "[&_svg]:shrink-0",
    ],
    input:
      "min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-fg read-only:cursor-default",
    addon: "flex shrink-0 items-center text-muted-fg",
  },
  variants: {
    variant: {
      outline: { frame: "border bg-transparent" },
      secondary: { frame: "bg-secondary text-secondary-fg" },
      ghost: { frame: "bg-transparent focus-within:bg-muted hover:bg-muted" },
    },
    size: {
      sm: {
        frame: "px-2.5 text-sm",
        addon: "text-sm [&_svg]:size-4",
      },
      md: {
        frame: "px-3 text-sm",
        addon: "text-sm [&_svg]:size-4",
      },
      lg: {
        frame: "px-3.5 text-base",
        addon: "text-base [&_svg]:size-5",
      },
    },
    // A single line has a fixed height and centers its content. A textarea
    // grows, so its content starts at the top.
    isMultiline: {
      false: { frame: "items-center" },
      true: { frame: "items-start", input: "resize-y", addon: "" },
    },
  },
  compoundVariants: [
    {
      isMultiline: false,
      size: "sm",
      class: { frame: "h-8", input: "h-full" },
    },
    {
      isMultiline: false,
      size: "md",
      class: { frame: "h-9", input: "h-full" },
    },
    {
      isMultiline: false,
      size: "lg",
      class: { frame: "h-11", input: "h-full" },
    },
    {
      isMultiline: true,
      size: "sm",
      class: { input: "py-1.5", addon: "py-1.5" },
    },
    { isMultiline: true, size: "md", class: { input: "py-2", addon: "py-2" } },
    {
      isMultiline: true,
      size: "lg",
      class: { input: "py-2.5", addon: "py-2.5" },
    },
  ],
  defaultVariants: { variant: "outline", size: "md", isMultiline: false },
});

2. Add the Text Field file

src/components/ui/text-field/text-field.tsxShow code
"use client";

import { type ReactNode, useRef, useState } from "react";
import {
  TextField as AriaTextField,
  type TextFieldProps as AriaTextFieldProps,
  FieldError,
  Input,
  Label,
  Text,
  TextArea,
  type ValidationResult,
} from "react-aria-components";
import { EyeIcon, EyeOffIcon } from "@/components/icons";
import { Button } from "@/components/ui/button/button";
import { cn } from "@/lib/cn";
import { textFieldStyles } from "@/types/text-field-styles";

export interface TextFieldProps
  extends Omit<AriaTextFieldProps, "children" | "className"> {
  label?: ReactNode;
  /** Help text under the field. */
  description?: ReactNode;
  /** Shown when the field is invalid. A function receives the validation result. */
  errorMessage?: string | ((validation: ValidationResult) => string);
  placeholder?: string;
  /** Look of the field. */
  variant?: "outline" | "secondary" | "ghost";
  /** Size of the field. */
  size?: "sm" | "md" | "lg";
  /** An icon or a short text before the input. */
  prefix?: ReactNode;
  /** An icon or a short text after the input. */
  suffix?: ReactNode;
  /** Render a `<textarea>` that can be resized, instead of a single line. */
  isMultiline?: boolean;
  /** Visible lines of a multiline field. */
  rows?: number;
  /** For `type="password"`: add a button that shows and hides the text. Defaults to `true`. */
  isRevealable?: boolean;
  /** With `maxLength`: show how many characters are used, under the field. */
  showCount?: boolean;
  className?: string;
}

/**
 * A field for typing text: a label, the input, help text and an error
 * message. Built on react-aria's TextField, so keyboard support, screen reader
 * support, form submission (`name`) and validation come from there.
 *
 * Add an icon or a short text before or after the input with `prefix` and
 * `suffix`. Use `type` for email, password, URL and so on, and `isMultiline`
 * for longer text.
 *
 * @example
 * <TextField label="Email" type="email" placeholder="you@example.com" />
 */
export function TextField({
  label,
  description,
  errorMessage,
  placeholder,
  variant,
  size = "md",
  prefix,
  suffix,
  isMultiline = false,
  rows = 3,
  isRevealable = true,
  showCount = false,
  className,
  type = "text",
  value,
  defaultValue,
  onChange,
  maxLength,
  ...props
}: TextFieldProps) {
  const styles = textFieldStyles({ variant, size, isMultiline });
  const inputRef = useRef<HTMLInputElement & HTMLTextAreaElement>(null);
  const [revealed, setRevealed] = useState(false);
  // Mirrors the text so the counter works whether the field is controlled or not.
  const [typed, setTyped] = useState(defaultValue ?? "");
  const length = (value ?? typed).length;

  const canReveal = type === "password" && isRevealable && !isMultiline;
  const Control = isMultiline ? TextArea : Input;

  return (
    <AriaTextField
      {...props}
      type={canReveal && revealed ? "text" : type}
      value={value}
      defaultValue={defaultValue}
      maxLength={maxLength}
      onChange={(next) => {
        setTyped(next);
        onChange?.(next);
      }}
      className={cn("group/text-field flex w-full flex-col gap-1.5", className)}
    >
      {label ? (
        <Label className="text-sm font-medium group-data-required/text-field:after:ml-0.5 group-data-required/text-field:after:text-danger group-data-required/text-field:after:content-['*']">
          {label}
        </Label>
      ) : null}
      {/* Clicking the padding or an addon should focus the input. */}
      {/* biome-ignore lint/a11y/noStaticElementInteractions: a mouse shortcut, the input is still reachable by keyboard */}
      <div
        className={styles.frame()}
        onMouseDown={(event) => {
          if (event.target === inputRef.current) return;
          if ((event.target as HTMLElement).closest("button")) return;
          event.preventDefault();
          inputRef.current?.focus();
        }}
      >
        {prefix ? <span className={styles.addon()}>{prefix}</span> : null}
        <Control
          ref={inputRef}
          placeholder={placeholder}
          rows={isMultiline ? rows : undefined}
          className={styles.input()}
        />
        {suffix ? <span className={styles.addon()}>{suffix}</span> : null}
        {canReveal ? (
          <Button
            isIcon
            variant="ghost"
            size={size === "lg" ? "sm" : "xs"}
            aria-label={revealed ? "Hide password" : "Show password"}
            aria-pressed={revealed}
            // The button sits at the end of the frame, with a little room.
            className="-mr-1.5 self-center"
            onPress={() => setRevealed((current) => !current)}
          >
            {revealed ? <EyeOffIcon /> : <EyeIcon />}
          </Button>
        ) : null}
      </div>
      {description || (showCount && maxLength) ? (
        <div className="flex items-start justify-between gap-3 text-sm text-muted-fg">
          {description ? (
            <Text slot="description">{description}</Text>
          ) : (
            <span />
          )}
          {showCount && maxLength ? (
            <span aria-hidden="true" className="tabular-nums">
              {length}/{maxLength}
            </span>
          ) : null}
        </div>
      ) : null}
      <FieldError className="text-sm text-danger">{errorMessage}</FieldError>
    </AriaTextField>
  );
}

It imports EyeIcon and EyeOffIcon from @/components/icons. Add those icons, or swap them for your own.

3. Use it

import { TextField } from "@/components/ui/text-field/text-field";

Anatomy

A text field is a framed input with optional content on both sides.

<TextField
  label="Website"
  description="Where people can find you."
  prefix="https://"
  suffix=".com"
  placeholder="example"
/>
PartRendered asNotes
LabellabelNames the field. Clicking it focuses the input.
PrefixspanAn icon or a short text before the input.
Inputinput or textareaWhere the user types.
Suffix / reveal buttonspan / ButtonAn icon or text after the input. A password field also gets a button that shows the text.
Description / countertext under the fieldHelp text on the left, and the character count on the right.
Errortext under the fieldShown while the field is invalid.

Without a label, give the field an aria-label so a screen reader can name it.

Examples

Live previews with code you can copy.

Usage

Label

Every field needs a name. Use label, or aria-label when the label is written elsewhere.

Description

Help text under the field.

Letters and numbers only. You can change it later.

Types

type picks the right keyboard on phones and lets the browser autofill.

Password

A password field gets a button that shows and hides the text. Set isRevealable to false to remove it.

Prefix and suffix

An icon or a short text inside the field, before or after the input. Clicking either focuses the input.

https://.com
$USD

Multiline

A textarea for longer text. rows sets how many lines are visible, and the user can resize it vertically.

Character count

With maxLength, the field stops accepting text at the limit. showCount adds a counter under it.

A short line about you.

Uncontrolled

Let the field keep its own text. Start with defaultValue, and give it a name to read the value from a form.

Controlled

Keep the text in your own state with value and onChange, so you can read it, set it or reset it from outside.

value: “Ada Lovelace”

Read only

The text can be selected and copied, but not changed. It is still submitted with a form.

Sizes

Variants

Disabled

Validation

Set isInvalid with an errorMessage. The field gets a red border and the message shows under it.

We will never share it.
Enter a valid email address.

Component API

Text Field takes the props below, plus everything the react-aria TextField accepts.

PropTypeDefault
labelReactNode-
descriptionReactNode-
errorMessagestring | (validation) => string-
placeholderstring-
type"text" | "email" | "password" | "tel" | "url" | "search""text"
valuestring-
defaultValuestring""
onChange(value: string) => void-
prefixReactNode-
suffixReactNode-
isMultilinebooleanfalse
rowsnumber3
isRevealablebooleantrue (password)
maxLengthnumber-
showCountbooleanfalse
namestring-
variant"outline" | "secondary" | "ghost""outline"
size"sm" | "md" | "lg""md"
autoFocusbooleanfalse
isDisabledbooleanfalse
isReadOnlybooleanfalse
isInvalidbooleanfalse
isRequiredbooleanfalse
aria-labelstring- (when there is no label)