# TextInput

A text input component that allows users to input custom text entries with a keyboard. Built with React Aria's `useTextField` hook for full accessibility and the Cube `tasty` style system for theming.

## When to Use

- Collect single-line text input from users (names, emails, URLs)
- Create multiline text areas for longer content
- Build forms with validation and field decoration
- Implement search inputs with icons and prefixes
- Handle password inputs with proper masking

## Component

---

### Properties

- **`value`** `string | null` — The text value in controlled mode. `null` clears the field and keeps it controlled
- **`defaultValue`** `string` — The default text value in uncontrolled mode
- **`isBuffered`** `boolean` (default: `true`) — Whether typed text is held locally until the controlled `value` catches up. This is what keeps the caret in place when the value round-trips through a store that re-renders a pass late; `onChange` still fires on every keystroke. Set to `false` for a caller that must see the field snap back to its own `value` the moment it declines a keystroke.
- **`placeholder`** `string` — Placeholder text when input is empty
- **`icon`** — Icon element rendered before the input
- **`prefix`** — Input decoration before the main input
- **`suffix`** — Input decoration after the main input
- **`suffixPosition`** `'before' | 'after'` (default: `before`) — Position of suffix relative to validation/loading state icons
- **`tooltip`** `string | TooltipProviderProps` — The input's own tooltip, a short hint about the value. It opens on hover over the field box and on keyboard focus, and describes the input. A string, or `TooltipProvider` props such as `title` and `placement` (`top` by default). A disabled input with a tooltip stays in the Tab order, marked `aria-disabled` and read-only rather than natively disabled, so the keyboard reaches the tooltip too. The info badge next to a field label is `labelTooltip`. See [With a Tooltip](#with-a-tooltip)
- **`type`** `'text' | 'password' | 'email' | 'url' | 'tel' | 'search'` (default: `text`) — Input type
- **`multiLine`** `boolean` (default: `false`) — Whether the input is multiline (textarea)
- **`rows`** `number` — Number of visible rows for multiline input
- **`resize`** `string` — CSS resize value for multiline input (e.g. `'vertical'`, `'none'`)
- **`size`** `'small' | 'medium' | 'large'` (default: `medium`) — Input size
- **`shape`** `'default' | 'plain'` (default: `default`) — Shape of the field box. `plain` is square with no border at rest, for a field set flush in a container that draws its edges, such as a toolbar or a panel header. Its border keeps its width and shows on focus and in a valid or invalid state, so nothing shifts
- **`autoComplete`** `string` — HTML [`autocomplete`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete) token that tells the browser what to autofill (`email`, `username`, `off`, …). The lowercase `autocomplete` alias is deprecated.
- **`isIdentifier`** `boolean` (default: `false`) — Whether the field holds an identifier, such as a name, key, token or attribute name, rather than prose. Turns off the browser's text services: `autocapitalize="none"`, `autocorrect="off"`, `spellcheck="false"` and `autocomplete="off"`, so a phone keyboard neither starts the value with a capital nor rewrites it, and the browser offers no past entries. An explicit `autoComplete`, `autoCorrect` or `spellCheck` prop, or any of the four attributes in `inputProps`, still wins. iOS still offers contact AutoFill above the keyboard: no attribute turns that off
- **`ignorePasswordManagers`** `boolean` (default: `false`) — Whether password manager extensions should leave the field alone: for the text field paired with a secret that is not the user's own login, such as a key ID or a client ID. See [PasswordInput](./PasswordInput.md#a-secret-that-is-not-a-login)
- **`maxLength`** `number` — Maximum number of characters allowed
- **`minLength`** `number` — Minimum number of characters required
- **`inputProps`** `Props` — Direct HTML props passed to the inner input element, merged over the props React Aria generates: a key you set wins, and event handlers are chained rather than replaced. The explicit `isDisabled`, `maxLength`, `minLength`, `autoFocus`, `rows` and `autoComplete` props win over the same attributes in `inputProps` when they are set; one left unset keeps the `inputProps` value
- **`inputRef`** `RefObject<HTMLInputElement | HTMLTextAreaElement>` — Ref to the inner input element
- **`wrapperRef`** `RefObject<HTMLDivElement>` — Ref to the input wrapper container
- **`loadingIndicator`** `ReactNode` — Rendered in place of the default loading icon while `isLoading` is set
- **`validate`** `(value: string) => ValidationError | true | null | undefined` — Client-side validation. React Aria sets `aria-invalid` from the returned errors at once; the invalid style and the message follow after the user edits or leaves the field, so an empty field does not open in red. An explicit `errorMessage` replaces the returned message, and an explicit `isInvalid` (or a form's validation) takes over from `validate` entirely
- **`onChange`** `function` — Callback fired when the input value changes
- **`onBlur`** `function` — Callback fired when the input loses focus
- **`onFocus`** `function` — Callback fired when the input receives focus
- **`onKeyDown`** `(e: KeyboardEvent) => void` — Callback fired when a key is pressed in the input. See [Keyboard Events](#keyboard-events)
- **`onKeyUp`** `(e: KeyboardEvent) => void` — Callback fired when a key is released in the input

#### Keyboard Events

`onKeyDown` and `onKeyUp` are attached to the `<input>` by React Aria's `useTextField`. TextInput has no key handling of its own, so the handler simply receives the event: `e.preventDefault()` cancels what the browser would do with the key, such as typing the character or submitting a surrounding form on `Enter`.

The handler receives React Aria's keyboard event rather than a plain React one, and once you pass `onKeyDown` React Aria stops the key's propagation after your handler: a parent's `onKeyDown` no longer sees it. Call `e.continuePropagation()` for the keys that should travel on.

`Escape` and `Tab` are the exception, as in every field: they go on to ancestors, so a surrounding `Dialog` still closes on `Escape` and moves focus on `Tab`. When your handler acts on one, call `e.preventDefault()` and it stays at the input:

```jsx
<TextInput
  label="Name"
  onKeyDown={(e) => {
    if (e.key === 'Enter') {
      e.preventDefault(); // keep a surrounding form from submitting
      commit();
    } else if (e.key === 'Escape') {
      e.preventDefault(); // keep a surrounding Dialog open
      revert();
    }
  }}
/>
```

The fields that do handle keys themselves (`ComboBox`, `SearchComboBox`, `TagInput`, `CommandTextArea`) run your `onKeyDown` first and skip their own handling for a key you prevent. `NumberInput` is the exception: React Aria runs its stepping and `Enter` commit before your handler. In all of them, a prevented `Escape` or `Tab` stays at the input.

### Base Properties

Supports [Base properties](../../BaseProperties.md)

### Field Properties

Supports all [Field properties](../../FieldProperties.md)

### Styling Properties

#### styles

Styles the input element. Its style props place and size the field: see [Field properties](../../FieldProperties.md).

**Sub-elements:**

- `InputWrapper` – container around the input field
- `Prefix` – wrapper around prefix content
- `Suffix` – wrapper around suffix content
- `State` – container for validation and loading icons
- `InputIcon` – wrapper around the main icon
- `ValidationIcon` – wrapper around validation state icons

#### inputStyles

Customizes the input element itself.

#### wrapperProps

Additional HTML props passed to the input wrapper container.

### Style Properties

These properties allow direct style application without using the `styles` prop:

- **Position:** `gridArea`, `order`, `gridColumn`, `gridRow`, `placeSelf`, `alignSelf`, `justifySelf`, `zIndex`, `margin`, `blockMargin`, `inlineMargin`, `inset`, `blockInset`, `inlineInset`, `position`, `scrollMargin`, `blockScrollMargin`, `inlineScrollMargin`, `scrollPadding`, `blockScrollPadding`, `inlineScrollPadding`
- **Dimension:** `width`, `height`, `blockSize`, `inlineSize`, `flexBasis`, `flexGrow`, `flexShrink`, `flex`

### Modifiers

The `mods` prop accepts the following modifiers you can override:

- **`focused`** `boolean` — Forces focus ring appearance.
- **`hovered`** `boolean` — Forces hover appearance.
- **`disabled`** `boolean` — Forces disabled appearance.
- **`readonly`** `boolean` — Set while `isReadOnly`: a recessed fill and a softer border, except in high contrast, and no hover state.
- **`invalid`** `boolean` — Forces invalid state styling.
- **`valid`** `boolean` — Forces valid state styling.
- **`loadable`** `boolean` — Set when a `loadingIndicator` is given. The loading icon itself follows `isLoading`, which has no modifier.
- **`multiline`** `boolean` — Set for a multiline input.
- **`prefix`** `boolean` — Indicates presence of prefix content.
- **`suffix`** `boolean` — Indicates presence of suffix content.
- **`shape`** `'default' | 'plain'` — Set from `shape`: `plain` drops the radius, and the border colour at rest.

## Variants

### Types

- `text` – Standard text input (default)
- `password` – Masked password input
- `email` – Email input with validation
- `url` – URL input with validation
- `tel` – Telephone number input
- `search` – Search input styling

### Sizes

- `small` – Compact height for dense interfaces
- `medium` – Standard height for most use cases
- `large` – Emphasized height for important inputs

### Shapes

- `default` – A rounded field box with a border
- `plain` – A square field box with no border at rest, for a field set flush in a container that draws its edges, such as a toolbar or a panel header. The border still marks focus and validity. See `SearchInput`'s Plain story.

```jsx
<Block styles={{ border: 'bottom' }}>
  <TextInput shape="plain" width="100%" aria-label="Title" placeholder="Untitled" />
</Block>
```

## Examples

### Basic Usage

```jsx
<TextInput
  label="Name"
  placeholder="Enter your name"
  onChange={(value) => console.log(value)}
/>
```

### With Icon

```jsx
import { IconMail } from '@tabler/icons-react';

<TextInput
  label="Email"
  type="email"
  icon={<IconMail />}
  placeholder="Enter your email"
/>
```

### With a Tooltip

`tooltip` gives an input without a visible label a short hint, such as what an empty value means or why the field is disabled. It is anchored to the field box, prefix and suffix included, so it never covers the text being typed.

```jsx
<TextInput aria-label="Axis minimum" placeholder="Auto" tooltip="Empty is the lowest value in the data" />
```

| When | What happens |
| --- | --- |
| The pointer hovers the field box | Opens after the tooltip delay |
| `Tab` moves focus to the input | Opens at once |
| A click or tap into the input | Doesn't open, and an open one closes: the user is about to type |
| Any key on the input | Closes until the next hover or keyboard focus |
| `Escape` while it is open | Closes the tooltip only. The key goes no further, so it doesn't clear a `SearchInput` or close a surrounding dialog |
| The input loses focus, or the pointer leaves | Closes |

A disabled field still shows its tooltip, which makes it the place to say why it can't be changed. While it has a tooltip it stays focusable, marked `aria-disabled` and read-only instead of natively disabled, so keyboard users can read the reason too. It takes no text, `NumberInput` doesn't step, `Enter` submits nothing, and a click on it or on its label doesn't focus it, as with a natively disabled field. Screen readers announce it as disabled and read-only. Not being natively disabled, its value is part of a plain `<form>`'s submitted data, except `NumberInput`'s, which submits through a hidden input that is disabled with the field. A ui-kit `Form` that handles its own submission is not affected. Without a tooltip, a disabled input is natively disabled and `Tab` skips it.

```jsx
<NumberInput isDisabled aria-label="Font size" tooltip="Turn data labels on to change this" />
```

Keep the tooltip a hint. It is never the field's name (give the input a `label` or `aria-label`), an error (`errorMessage`) or anything the user needs to fill the field in (`description`): touch users never see it. When keyboard users must learn why a field can't be edited and a tooltip is not enough, show it as a `description`, or use `isReadOnly`. Prefer `tooltip` to wrapping the input in `TooltipProvider`: a disabled input takes no trigger props from a wrapper, so that tooltip never opens.

To switch the tooltip off and on while the input can have focus, keep `tooltip` set with a non-empty `title` and toggle its `isDisabled` (`tooltip={{ title, isDisabled: !isEmpty }}`). Setting and clearing `tooltip`, or emptying its `title`, remounts the field box, and the input loses focus mid-typing.

### Multiline Text Area

```jsx
<TextInput
  label="Description"
  multiLine
  rows={4}
  placeholder="Enter description..."
/>
```

### Identifier

For a name, key, token or attribute name, `isIdentifier` keeps a phone keyboard from capitalizing or autocorrecting the value and the browser from offering past entries.

```jsx
<TextInput label="Deployment name" isIdentifier />
```

### With Validation

```jsx
<TextInput
  label="Username"
  isRequired
  isInvalid
  message="Username must be at least 3 characters"
/>
```

## Accessibility

### Keyboard Navigation

- `Tab` – Moves focus to the input field. A disabled field takes focus only while it has a `tooltip`, which then opens
- `Shift + Tab` – Moves focus away from the input
- Standard text editing shortcuts (Ctrl+A, Ctrl+C, etc.)

### Pointer

A press anywhere inside the field's border focuses the input, including the prefix and suffix areas and their icons. Presses on interactive content there, such as a button in `suffix`, stay with that content.

### Screen Reader Support

- Announces role "textbox" or "searchbox" for search inputs
- Announces label, description, and validation messages
- State changes like "invalid" or "required" are announced
- The loading indicator is visual only: `isLoading` is not announced, so announce a long-running check yourself if users need to hear it

### ARIA Properties

- `aria-label`, `aria-labelledby` – Accessible name for the input
- `aria-describedby` – Links to description and error messages
- `aria-invalid` – Managed automatically based on `isInvalid` and `validate`
- `aria-required` – Set when `isRequired` is true
- Additional ARIA attributes supported by React Aria's `useTextField`

## Best Practices

1. **Do**: Provide clear labels and helpful placeholder text

   ```jsx
   <TextInput label="Email Address" placeholder="you@example.com" />
   ```

2. **Don't**: Use placeholder text as the only label

   ```jsx
   {/* Avoid this */}
   <TextInput placeholder="Enter your email" />
   ```

3. **Accessibility**: Always provide proper labels for screen readers
4. **Validation**: Use `isInvalid` / `isValid` and `errorMessage` for user feedback
5. **Performance**: Use `defaultValue` for uncontrolled inputs when possible

## Integration with Forms

This component supports all [Field properties](../../FieldProperties.md) when used within a Form.

## Suggested Improvements

- Provide `maxLength` indicator with visible character count
- Support for input masks and formatting
- Built-in debouncing for onChange events

## Related Components

- [TextArea](./TextArea.md) – Dedicated multiline text input
- [SearchInput](./SearchInput.md) – Specialized search input with clear button
- [PasswordInput](./PasswordInput.md) – Enhanced password input with show/hide toggle
- [NumberInput](./NumberInput.md) – Numeric input with increment/decrement controls
