dotUI
dotUI
beta
  1. Components
  2. Inputs
  3. TextField

TextField

TextField allows a user to enter a plain text value with a keyboard.

<TextField label="Email" placeholder="hello@mehdibha.com" />

Installation

Install the following dependencies:

npm install react-aria-components

Copy and paste the following code into your project.

"use client";

import * as React from "react";
import {
  TextField as AriaTextField,
  type TextFieldProps as AriaTextFieldProps,
} from "react-aria-components";
import { tv, type VariantProps } from "tailwind-variants";
import { Field, type FieldProps } from "./field";
import { InputRoot, Input, type inputStyles } from "./input";

const textFieldStyles = tv({
  base: "flex flex-col gap-2 items-start w-48",
});

type TextFieldProps = TextFieldRootProps &
  Omit<FieldProps, "children"> &
  VariantProps<typeof inputStyles> & {
    prefix?: React.ReactNode;
    suffix?: React.ReactNode;
    isLoading?: boolean;
    loaderPosition?: "prefix" | "suffix";
    placeholder?: string;
  };
const TextField = React.forwardRef<HTMLInputElement, TextFieldProps>(
  (
    {
      className,
      size,
      placeholder,
      label,
      description,
      errorMessage,
      prefix,
      suffix,
      isLoading,
      loaderPosition = "suffix",
      necessityIndicator,
      contextualHelp,
      ...props
    },
    ref
  ) => {
    return (
      <TextFieldRoot className={className} {...props}>
        {({ isRequired }) => (
          <Field
            label={label}
            description={description}
            errorMessage={errorMessage}
            isRequired={isRequired}
            necessityIndicator={necessityIndicator}
            contextualHelp={contextualHelp}
          >
            <InputRoot
              size={size}
              prefix={prefix}
              suffix={suffix}
              isLoading={isLoading}
              loaderPosition={loaderPosition}
            >
              <Input ref={ref} placeholder={placeholder} />
            </InputRoot>
          </Field>
        )}
      </TextFieldRoot>
    );
  }
);
TextField.displayName = "TextField";

type TextFieldRootProps = Omit<AriaTextFieldProps, "className"> & {
  className?: string;
};
const TextFieldRoot = React.forwardRef<React.ElementRef<typeof AriaTextField>, TextFieldRootProps>(
  ({ className, ...props }, ref) => {
    return <AriaTextField ref={ref} className={textFieldStyles({ className })} {...props} />;
  }
);
TextFieldRoot.displayName = "TextFieldRoot";

export type { TextFieldProps, TextFieldRootProps };
export { TextField, TextFieldRoot };

Update the import paths to match your project setup.

Usage

Use a TextField to allow users to input custom text entries with a keyboard.

Options

Size

Use the size prop to control the size of the TextField. The default size is "md".

<TextField size="sm" />
<TextField size="md" />
<TextField size="lg" />

Prefix and suffix

To add additional context for the TextField, use the prefix and suffix props.

<TextField prefix={<span>https://</span>} />
<TextField suffix={<span>@rcopy.dev</span>} />
<TextField suffix={<ClearButton />} />

Label

A visual label can be provided for the TextField using the label prop, or a hidden label using aria-label prop.

<TextField label="Email" />
<TextField aria-label="Email" />

Description

A description can be supplied to TextField via the description prop. The description is always visible unless the isInvalid prop is true and an error message is provided.

<TextField label="Email" description="Enter your email." />

Contextual help

A ContextualHelp element may be placed next to the label to provide additional information or help about a TextField.

<TextField label="Password" contextualHelp={<ContextualHelp />} />

Error message

An errorMessage can be supplied to TextField, which will be displayed when the isInvalid prop is set to true.

<TextField
  label="Email"
  isInvalid
  errorMessage="This email is already taken."
/>

Loading

Use the isLoading prop to control the loading state of the TextField. Use the loaderPosition prop to control the position of the loader.

<TextField isLoading loaderPosition="prefix" />
<TextField isLoading loaderPosition="suffix" />

Disabled

Use the isDisabled prop to disable the TextField.

<TextField isDisabled />

ReadOnly

The isReadOnly boolean prop makes the TextField's text content immutable. Unlike isDisabled, the TextField remains focusable and the contents can still be copied.

<TextField isReadOnly />

Required

Use the isRequired prop to mark the TextField as required. Use the necessityIndicator prop to control the visual style of the required state.

<TextField label="Email" isRequired />
<TextField label="Email" isRequired necessityIndicator="icon" />
<TextField label="Email" isRequired necessityIndicator="label" />
<TextField label="Email" necessityIndicator="label" />

Uncontrolled

Use the defaultValue prop to set the default input value.

<TextField label="Name" defaultValue="Mehdi" />

Controlled

Use the value and onChange props to control the value of the input.

const [inputValue, setInputValue] = React.useState("Hello world!");
return (
  <TextField
    value={inputValue}
    onChange={(text) => {
      setInputValue(text);
    }}
  />
);

Composition

If you need to customize things further, you can drop down to the composition level.

<TextFieldRoot>
  <Label>Email</Label>
  <InputRoot>
    <Input />
  </InputRoot>
  <Description>Enter your email.</Description>
</TextFieldRoot>

API Reference

PropTypeDefaultDescription
size
"sm" | "md" | "lg"
"md"
The size of the input.
prefix
ReactNode
-
A visual to display before the input.
suffix
ReactNode
-
A visual to display after the input.
label
ReactNode
The content to display as the label.
description
ReactNode
A description for the field. Provides a hint such as specific requirements for what to choose.
errorMessage
ReactNode | (v: ValidationResult) => ReactNode
An error message for the field.
loaderPosition
"prefix" | "suffix"
"suffix"
The loader position
isLoading
boolean
-
Whether the TextField is in a pending state.
isInvalid
boolean
-
Whether the value is invalid.
isDisabled
boolean
-
Whether the input is disabled.
isReadOnly
boolean
-
Whether the input can be selected but not changed by the user.
isRequired
boolean
-
Whether user input is required on the input before form submission.
validate
(value: string) => ValidationError | true | null | undefined
-
A function that returns an error message if a given value is invalid. Validation errors are displayed to the user when the form is submitted if validationBehavior="native". For realtime validation, use the isInvalid prop instead.
autoFocus
boolean
-
Whether the element should receive focus on render.
value
string
-
The current value (controlled).
defaultValue
string
-
The default value (uncontrolled).
autoComplete
string
-
Describes the type of autocomplete functionality the input should provide if any.
maxLength
number
-
The maximum number of characters supported by the input.
minLength
number
-
The minimum number of characters required by the input.
pattern
string
-
Regex pattern that the value of the input must match to be valid.
type
'text' | 'search' | 'url' | 'tel' | 'email' | 'password' | string & {}
-
The type of input to render.
inputMode
'none' | 'text' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search'
-
Hints at the type of data that might be entered by the user while editing the element or its contents.
name
string
-
The name of the input element, used when submitting an HTML form.
validationBehavior
'native' | 'aria'
'native'
Whether to use native HTML form validation to prevent form submission when the value is missing or invalid, or mark the field as required or invalid via ARIA.
children
ReactNode | (values: TextFieldRenderProps & {defaultChildren: ReactNode | undefined}) => ReactNode
-
The children of the component. A function may be provided to alter the children based on component state.
className
string
-
The CSS className for the element.
style
CSSProperties | (values: TextFieldRenderProps & {defaultStyle: CSSProperties}) => CSSProperties
-
The inline style for the element. A function may be provided to compute the style based on component state.
EventTypeDescription
onFocus
(e: FocusEvent<Target>) => void
Handler that is called when the element receives focus.
onBlur
(e: FocusEvent<Target>) => void
Handler that is called when the element loses focus.
onFocusChange
(isFocused: boolean) => void
Handler that is called when the element's focus status changes.
onKeyDown
(e: KeyboardEvent) => void
Handler that is called when a key is pressed.
onKeyUp
(e: KeyboardEvent) => void
Handler that is called when a key is released.
onChange
(value: T) => void
Handler that is called when the value changes.
onCopy
ClipboardEventHandler<HTMLInputElement>
Handler that is called when the user copies text.
onCut
ClipboardEventHandler<HTMLInputElement>
Handler that is called when the user cuts text.
onPaste
ClipboardEventHandler<HTMLInputElement>
Handler that is called when the user pastes text.
onCompositionStart
CompositionEventHandler<HTMLInputElement>
Handler that is called when a text composition system starts a new text composition session.
onCompositionEnd
CompositionEventHandler<HTMLInputElement>
Handler that is called when a text composition system completes or cancels the current text composition session.
onCompositionUpdate
CompositionEventHandler<HTMLInputElement>
Handler that is called when a new character is received in the current text composition session.
onSelect
ReactEventHandler<HTMLInputElement>
Handler that is called when text in the input is selected.
onBeforeInput
FormEventHandler<HTMLInputElement>
Handler that is called when the input value is about to be modified.
onInput
FormEventHandler<HTMLInputElement>
Handler that is called when the input value is modified.
Data attributeDescription
[data-disabled]
Whether the text field is disabled.
[data-invalid]
Whether the text field is invalid.
[data-readonly]
Whether the text field is read only.
[data-required]
Whether the text field is required.

Built by mehdibha. The source code is available on GitHub.