beta

TextField

A text field allows a user to enter a plain text value with a keyboard.

installyarn add react-aria-components
version1.0.0-beta.2
usageimport {TextField} from 'react-aria-components'

Example#


import {TextField, Label, Input} from 'react-aria-components';

<TextField>
  <Label>First name</Label>
  <Input />
</TextField>
import {
  Input,
  Label,
  TextField
} from 'react-aria-components';

<TextField>
  <Label>First name</Label>
  <Input />
</TextField>
import {
  Input,
  Label,
  TextField
} from 'react-aria-components';

<TextField>
  <Label>
    First name
  </Label>
  <Input />
</TextField>
Show CSS
.react-aria-TextField {
  --field-border: var(--spectrum-alias-border-color);
  --field-border-disabled: var(--spectrum-alias-border-color-disabled);
  --field-background: var(--spectrum-global-color-gray-50);
  --text-color: var(--spectrum-alias-text-color);
  --text-color-disabled: var(--spectrum-alias-text-color-disabled);
  --focus-ring-color: slateblue;
  --invalid-color: var(--spectrum-global-color-red-600);

  display: flex;
  flex-direction: column;
  width: fit-content;

  .react-aria-Input,
  .react-aria-TextArea {
    padding: 0.286rem;
    margin: 0;
    border: 1px solid var(--field-border);
    border-radius: 6px;
    background: var(--field-background);
    font-size: 1.143rem;
    color: var(--text-color);

    &[data-invalid] {
      border-color: var(--invalid-color);
    }

    &[data-focused] {
      outline: none;
      border-color: var(--focus-ring-color);
      box-shadow: 0 0 0 1px var(--focus-ring-color);
    }

    &[data-disabled] {
      border-color: var(--field-border-disabled);
      color: var(--text-color-disabled);
    }
  }

  [slot=description] {
    font-size: 12px;
  }

  [slot=errorMessage] {
    font-size: 12px;
    color: var(--invalid-color);
  }
}

@media (forced-colors: active) {
  .react-aria-TextField {
    --field-border: ButtonBorder;
    --field-border-disabled: GrayText;
    --field-background: Field;
    --text-color: FieldText;
    --text-color-disabled: GrayText;
    --focus-ring-color: Highlight;
    --invalid-color: LinkText;
  }
}
.react-aria-TextField {
  --field-border: var(--spectrum-alias-border-color);
  --field-border-disabled: var(--spectrum-alias-border-color-disabled);
  --field-background: var(--spectrum-global-color-gray-50);
  --text-color: var(--spectrum-alias-text-color);
  --text-color-disabled: var(--spectrum-alias-text-color-disabled);
  --focus-ring-color: slateblue;
  --invalid-color: var(--spectrum-global-color-red-600);

  display: flex;
  flex-direction: column;
  width: fit-content;

  .react-aria-Input,
  .react-aria-TextArea {
    padding: 0.286rem;
    margin: 0;
    border: 1px solid var(--field-border);
    border-radius: 6px;
    background: var(--field-background);
    font-size: 1.143rem;
    color: var(--text-color);

    &[data-invalid] {
      border-color: var(--invalid-color);
    }

    &[data-focused] {
      outline: none;
      border-color: var(--focus-ring-color);
      box-shadow: 0 0 0 1px var(--focus-ring-color);
    }

    &[data-disabled] {
      border-color: var(--field-border-disabled);
      color: var(--text-color-disabled);
    }
  }

  [slot=description] {
    font-size: 12px;
  }

  [slot=errorMessage] {
    font-size: 12px;
    color: var(--invalid-color);
  }
}

@media (forced-colors: active) {
  .react-aria-TextField {
    --field-border: ButtonBorder;
    --field-border-disabled: GrayText;
    --field-background: Field;
    --text-color: FieldText;
    --text-color-disabled: GrayText;
    --focus-ring-color: Highlight;
    --invalid-color: LinkText;
  }
}
.react-aria-TextField {
  --field-border: var(--spectrum-alias-border-color);
  --field-border-disabled: var(--spectrum-alias-border-color-disabled);
  --field-background: var(--spectrum-global-color-gray-50);
  --text-color: var(--spectrum-alias-text-color);
  --text-color-disabled: var(--spectrum-alias-text-color-disabled);
  --focus-ring-color: slateblue;
  --invalid-color: var(--spectrum-global-color-red-600);

  display: flex;
  flex-direction: column;
  width: fit-content;

  .react-aria-Input,
  .react-aria-TextArea {
    padding: 0.286rem;
    margin: 0;
    border: 1px solid var(--field-border);
    border-radius: 6px;
    background: var(--field-background);
    font-size: 1.143rem;
    color: var(--text-color);

    &[data-invalid] {
      border-color: var(--invalid-color);
    }

    &[data-focused] {
      outline: none;
      border-color: var(--focus-ring-color);
      box-shadow: 0 0 0 1px var(--focus-ring-color);
    }

    &[data-disabled] {
      border-color: var(--field-border-disabled);
      color: var(--text-color-disabled);
    }
  }

  [slot=description] {
    font-size: 12px;
  }

  [slot=errorMessage] {
    font-size: 12px;
    color: var(--invalid-color);
  }
}

@media (forced-colors: active) {
  .react-aria-TextField {
    --field-border: ButtonBorder;
    --field-border-disabled: GrayText;
    --field-background: Field;
    --text-color: FieldText;
    --text-color-disabled: GrayText;
    --focus-ring-color: Highlight;
    --invalid-color: LinkText;
  }
}

Features#


Text fields can be built with <input> or <textarea> and <label> elements, but you must manually ensure that they are semantically connected via ids for accessibility. TextField helps automate this, and handle other accessibility features while allowing for custom styling.

  • Accessible – Uses a native <input> element. Label, description, and error message elements are automatically associated with the field.
  • Custom validation – Required and invalid states are exposed to assistive technology via ARIA.

Anatomy#


ValueLabelInputLabelHelp textDescription or error message

Text fields consist of an input element and a label. TextField automatically manages the relationship between the two elements using the for attribute on the <label> element and the aria-labelledby attribute on the <input> element.

TextField also supports optional description and error message elements, which can be used to provide more context about the field, and any validation messages. These are linked with the input via the aria-describedby attribute.

import {TextField, Label, Input, Button, Text} from 'react-aria-components';

<TextField>
  <Label />
  <Input />
  <Text slot="description" />
  <Text slot="errorMessage" />
</TextField>
import {
  Button,
  Input,
  Label,
  Text,
  TextField
} from 'react-aria-components';

<TextField>
  <Label />
  <Input />
  <Text slot="description" />
  <Text slot="errorMessage" />
</TextField>
import {
  Button,
  Input,
  Label,
  Text,
  TextField
} from 'react-aria-components';

<TextField>
  <Label />
  <Input />
  <Text slot="description" />
  <Text slot="errorMessage" />
</TextField>

If there is no visual label, an aria-label or aria-labelledby prop must be passed instead to identify the element to screen readers.

Composed components#

A TextField uses the following components, which may also be used standalone or reused in other components.

Label
A label provides context for an input element.
Input
An input allows a user to enter a plain text value with a keyboard.

Reusable wrappers#


If you will use a TextField in multiple places in your app, you can wrap all of the pieces into a reusable component. This way, the DOM structure, styling code, and other logic are defined in a single place and reused everywhere to ensure consistency.

This example wraps TextField and all of its children together into a single component which accepts a label prop, which is passed to the right place. It also shows how to use the description and errorMessage slots to render help text (see below for details).

import type {TextFieldProps} from 'react-aria-components';
import {Text} from 'react-aria-components';

interface MyTextFieldProps extends TextFieldProps {
  label?: string;
  description?: string;
  errorMessage?: string;
}

function MyTextField(
  { label, description, errorMessage, ...props }: MyTextFieldProps
) {
  return (
    <TextField {...props}>
      <Label>{label}</Label>
      <Input />
      {description && <Text slot="description">{description}</Text>}
      {errorMessage && <Text slot="errorMessage">{errorMessage}</Text>}
    </TextField>
  );
}

<MyTextField label="Name" />
import type {TextFieldProps} from 'react-aria-components';
import {Text} from 'react-aria-components';

interface MyTextFieldProps extends TextFieldProps {
  label?: string;
  description?: string;
  errorMessage?: string;
}

function MyTextField(
  { label, description, errorMessage, ...props }:
    MyTextFieldProps
) {
  return (
    <TextField {...props}>
      <Label>{label}</Label>
      <Input />
      {description && (
        <Text slot="description">{description}</Text>
      )}
      {errorMessage && (
        <Text slot="errorMessage">{errorMessage}</Text>
      )}
    </TextField>
  );
}

<MyTextField label="Name" />
import type {TextFieldProps} from 'react-aria-components';
import {Text} from 'react-aria-components';

interface MyTextFieldProps
  extends
    TextFieldProps {
  label?: string;
  description?: string;
  errorMessage?: string;
}

function MyTextField(
  {
    label,
    description,
    errorMessage,
    ...props
  }: MyTextFieldProps
) {
  return (
    <TextField
      {...props}
    >
      <Label>
        {label}
      </Label>
      <Input />
      {description && (
        <Text slot="description">
          {description}
        </Text>
      )}
      {errorMessage && (
        <Text slot="errorMessage">
          {errorMessage}
        </Text>
      )}
    </TextField>
  );
}

<MyTextField label="Name" />

Value#


Default value#

A TextField's value is empty by default, but an initial, uncontrolled, value can be provided using the defaultValue prop.

<MyTextField
  label="Email"
  defaultValue="me@email.com" />
<MyTextField
  label="Email"
  defaultValue="me@email.com" />
<MyTextField
  label="Email"
  defaultValue="me@email.com"
/>

Controlled value#

The value prop can be used to make the value controlled. The onChange event is fired when the user edits the text, and receives the new value.

function Example() {
  let [text, setText] = React.useState('');

  return (
    <>
      <MyTextField label="Your text" onChange={setText} />
      <p>Mirrored text: {text}</p>
    </>
  );
}
function Example() {
  let [text, setText] = React.useState('');

  return (
    <>
      <MyTextField label="Your text" onChange={setText} />
      <p>Mirrored text: {text}</p>
    </>
  );
}
function Example() {
  let [text, setText] =
    React.useState('');

  return (
    <>
      <MyTextField
        label="Your text"
        onChange={setText}
      />
      <p>
        Mirrored text:
        {' '}
        {text}
      </p>
    </>
  );
}

HTML forms#

TextField supports the name prop for integration with HTML forms. In addition, attributes such as type, pattern, inputMode, and others are passed through to the underlying <input> element.

<MyTextField label="Email" name="email" type="email" />
<MyTextField label="Email" name="email" type="email" />
<MyTextField
  label="Email"
  name="email"
  type="email"
/>

Validation#


Description#

The description slot can be used to associate additional help text with a text field.

<TextField>
  <Label>Email</Label>
  <Input />
  <Text slot="description">
    Enter an email for us to contact you about your order.
  </Text></TextField>
<TextField>
  <Label>Email</Label>
  <Input />
  <Text slot="description">
    Enter an email for us to contact you about your order.
  </Text></TextField>
<TextField>
  <Label>Email</Label>
  <Input />
  <Text slot="description">
    Enter an email for
    us to contact you
    about your order.
  </Text></TextField>

Error message#

The errorMessage slot can be used to help the user fix a validation error. It should be combined with the isInvalid prop to semantically mark the input element as invalid for assistive technologies.

<TextField isInvalid>
  <Label>Email</Label>
  <Input />
  <Text slot="errorMessage">Please enter a valid email address.</Text></TextField>
<TextField isInvalid>
  <Label>Email</Label>
  <Input />
  <Text slot="errorMessage">
    Please enter a valid email address.
  </Text></TextField>
<TextField isInvalid>
  <Label>Email</Label>
  <Input />
  <Text slot="errorMessage">
    Please enter a
    valid email
    address.
  </Text></TextField>

Required#

A TextField can be marked as required using the isRequired prop. This is exposed to assistive technologies by React Aria. It's your responsibility to add additional visual styling if needed.

<MyTextField label="Email" isRequired />
<MyTextField label="Email" isRequired />
<MyTextField
  label="Email"
  isRequired
/>

Disabled#


A TextField can be disabled using the isDisabled prop.

<MyTextField label="Email" isDisabled />
<MyTextField label="Email" isDisabled />
<MyTextField
  label="Email"
  isDisabled
/>

Read only#

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

<MyTextField label="Email" defaultValue="abc@adobe.com" isReadOnly />
<MyTextField
  label="Email"
  defaultValue="abc@adobe.com"
  isReadOnly
/>
<MyTextField
  label="Email"
  defaultValue="abc@adobe.com"
  isReadOnly
/>

Multi-line#


TextField supports using the TextArea component in place of Input for multi-line text input.

import {TextField, Label, TextArea} from 'react-aria-components';

<TextField>
  <Label>Comment</Label>
  <TextArea />
</TextField>
import {
  Label,
  TextArea,
  TextField
} from 'react-aria-components';

<TextField>
  <Label>Comment</Label>
  <TextArea />
</TextField>
import {
  Label,
  TextArea,
  TextField
} from 'react-aria-components';

<TextField>
  <Label>
    Comment
  </Label>
  <TextArea />
</TextField>

Props#


TextField#

NameTypeDescription
isInvalidbooleanWhether the value is invalid.
isDisabledbooleanWhether the input is disabled.
isReadOnlybooleanWhether the input can be selected but not changed by the user.
isRequiredbooleanWhether user input is required on the input before form submission.
autoFocusbooleanWhether the element should receive focus on render.
valuestringThe current value (controlled).
defaultValuestringThe default value (uncontrolled).
autoCompletestringDescribes the type of autocomplete functionality the input should provide if any. See MDN.
maxLengthnumberThe maximum number of characters supported by the input. See MDN.
minLengthnumberThe minimum number of characters required by the input. See MDN.
patternstringRegex pattern that the value of the input must match to be valid. See MDN.
type'text''search''url''tel''email''password'string{}The type of input to render. See MDN.
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. See MDN.
namestringThe name of the input element, used when submitting an HTML form. See MDN.
childrenReactNode( (values: TextFieldRenderProps )) => ReactNodeThe children of the component. A function may be provided to alter the children based on component state.
classNamestring( (values: TextFieldRenderProps )) => stringThe CSS className for the element. A function may be provided to compute the class based on component state.
styleCSSProperties( (values: TextFieldRenderProps )) => CSSPropertiesThe inline style for the element. A function may be provided to compute the style based on component state.
Events
NameTypeDescription
onFocus( (e: FocusEvent<Target> )) => voidHandler that is called when the element receives focus.
onBlur( (e: FocusEvent<Target> )) => voidHandler that is called when the element loses focus.
onFocusChange( (isFocused: boolean )) => voidHandler that is called when the element's focus status changes.
onKeyDown( (e: KeyboardEvent )) => voidHandler that is called when a key is pressed.
onKeyUp( (e: KeyboardEvent )) => voidHandler that is called when a key is released.
onChange( (value: T )) => voidHandler that is called when the value changes.
onCopyClipboardEventHandler<HTMLInputElement>Handler that is called when the user copies text. See MDN.
onCutClipboardEventHandler<HTMLInputElement>Handler that is called when the user cuts text. See MDN.
onPasteClipboardEventHandler<HTMLInputElement>Handler that is called when the user pastes text. See MDN.
onCompositionStartCompositionEventHandler<HTMLInputElement>Handler that is called when a text composition system starts a new text composition session. See MDN.
onCompositionEndCompositionEventHandler<HTMLInputElement>Handler that is called when a text composition system completes or cancels the current text composition session. See MDN.
onCompositionUpdateCompositionEventHandler<HTMLInputElement>Handler that is called when a new character is received in the current text composition session. See MDN.
onSelectReactEventHandler<HTMLInputElement>Handler that is called when text in the input is selected. See MDN.
onBeforeInputFormEventHandler<HTMLInputElement>Handler that is called when the input value is about to be modified. See MDN.
onInputFormEventHandler<HTMLInputElement>Handler that is called when the input value is modified. See MDN.
Layout
NameTypeDescription
slotstringnull

A slot name for the component. Slots allow the component to receive props from a parent component. An explicit null value indicates that the local props completely override all props received from a parent.

Accessibility
NameTypeDescription
idstringThe element's unique identifier. See MDN.
excludeFromTabOrderboolean

Whether to exclude the element from the sequential tab order. If true, the element will not be focusable via the keyboard by tabbing. This should be avoided except in rare scenarios where an alternative means of accessing the element or its functionality via the keyboard is available.

aria-activedescendantstringIdentifies the currently active element when DOM focus is on a composite widget, textbox, group, or application.
aria-autocomplete'none''inline''list''both'

Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be presented if they are made.

aria-haspopupboolean'false''true''menu''listbox''tree''grid''dialog'Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element.
aria-labelstringDefines a string value that labels the current element.
aria-labelledbystringIdentifies the element (or elements) that labels the current element.
aria-describedbystringIdentifies the element (or elements) that describes the object.
aria-detailsstringIdentifies the element (or elements) that provide a detailed, extended description for the object.
aria-errormessagestringIdentifies the element that provides an error message for the object.

Label#

A <Label> accepts all HTML attributes.

Input#

An <Input> accepts all HTML attributes.

Text#

<Text> accepts all HTML attributes.

Styling#


React Aria components can be styled in many ways, including using CSS classes, inline styles, utility classes (e.g. Tailwind), CSS-in-JS (e.g. Styled Components), etc. By default, all components include a builtin className attribute which can be targeted using CSS selectors. These follow the react-aria-ComponentName naming convention.

.react-aria-TextField {
  /* ... */
}
.react-aria-TextField {
  /* ... */
}
.react-aria-TextField {
  /* ... */
}

A custom className can also be specified on any component. This overrides the default className provided by React Aria with your own.

<TextField className="my-textfield">
  {/* ... */}
</TextField>
<TextField className="my-textfield">
  {/* ... */}
</TextField>
<TextField className="my-textfield">
  {/* ... */}
</TextField>

In addition, some components support multiple UI states (e.g. focused, placeholder, readonly, etc.). React Aria components expose states using data attributes, which you can target in CSS selectors. For example:

input[data-hovered] {
  /* ... */
}

input[data-disabled] {
  /* ... */
}
input[data-hovered] {
  /* ... */
}

input[data-disabled] {
  /* ... */
}
input[data-hovered] {
  /* ... */
}

input[data-disabled] {
  /* ... */
}

The states, selectors, and render props for each component used in a TextField are documented below.

TextField#

A TextField can be targeted with the .react-aria-TextField CSS selector, or by overriding with a custom className. It supports the following states:

NameCSS SelectorDescription
isDisabled[data-disabled]Whether the text field is disabled.
isInvalid[data-invalid]Whether the value is invalid.

Label#

A Label can be targeted with the .react-aria-Label CSS selector, or by overriding with a custom className.

Input#

An Input can be targeted with the .react-aria-Input CSS selector, or by overriding with a custom className. It supports the following states:

NameCSS SelectorDescription
isHovered[data-hovered]Whether the input is currently hovered with a mouse.
isFocused[data-focused]Whether the input is focused, either via a mouse or keyboard.
isFocusVisible[data-focus-visible]Whether the input is keyboard focused.
isDisabled[data-disabled]Whether the input is disabled.
isInvalid[data-invalid]Whether the input is invalid.

TextArea#

An TextArea can be targeted with the .react-aria-TextArea CSS selector, or by overriding with a custom className. It supports the same states as Input described above.

Text#

The help text elements within a TextField can be targeted with the [slot=description] and [slot=errorMessage] CSS selectors, or by adding a custom className.

Advanced customization#


Composition#

If you need to customize one of the components within a TextField, such as Label or Input, in many cases you can create a wrapper component. This lets you customize the props passed to the component.

function MyInput(props) {
  return <Input {...props} className="my-input" />
}
function MyInput(props) {
  return <Input {...props} className="my-input" />
}
function MyInput(props) {
  return (
    <Input
      {...props}
      className="my-input"
    />
  );
}

Contexts#

All React Aria Components export a corresponding context that can be used to send props to them from a parent element. This enables you to build your own compositional APIs similar to those found in React Aria Components itself. You can send any prop or ref via context that you could pass to the corresponding component. The local props and ref on the component are merged with the ones passed via context, with the local props taking precedence (following the rules documented in mergeProps).

ComponentContextPropsRef
TextFieldTextFieldContextTextFieldPropsHTMLDivElement

This example shows a FieldGroup component that renders a group of text fields with a title and optional error message. It uses the useId hook to generate a unique id for the error message. All of the child TextFields are marked invalid and associated with the error message via the aria-describedby attribute passed to the TextFieldContext provider.

import {TextFieldContext} from 'react-aria-components';
import {useId} from 'react-aria';

interface FieldGroupProps {
  title?: string;
  children?: React.ReactNode;
  errorMessage?: string;
}

function FieldGroup({ title, children, errorMessage }: FieldGroupProps) {
  let errorId = useId();
  return (
    <fieldset>
      <legend>{title}</legend>
      <TextFieldContext.Provider
        value={{
          isInvalid: !!errorMessage,
          'aria-describedby': errorMessage ? errorId : undefined
        }}
      >        {children}
      </TextFieldContext.Provider>
      {errorMessage && (
        <small id={errorId} className="invalid">{errorMessage}</small>
      )}
    </fieldset>
  );
}

<FieldGroup title="Account details" errorMessage="Invalid account details.">
  <MyTextField label="Name" defaultValue="Devon" />
  <MyTextField label="Email" defaultValue="devon@example.com" />
</FieldGroup>
import {TextFieldContext} from 'react-aria-components';
import {useId} from 'react-aria';

interface FieldGroupProps {
  title?: string;
  children?: React.ReactNode;
  errorMessage?: string;
}

function FieldGroup(
  { title, children, errorMessage }: FieldGroupProps
) {
  let errorId = useId();
  return (
    <fieldset>
      <legend>{title}</legend>
      <TextFieldContext.Provider
        value={{
          isInvalid: !!errorMessage,
          'aria-describedby': errorMessage
            ? errorId
            : undefined
        }}
      >        {children}
      </TextFieldContext.Provider>
      {errorMessage && (
        <small id={errorId} className="invalid">
          {errorMessage}
        </small>
      )}
    </fieldset>
  );
}

<FieldGroup
  title="Account details"
  errorMessage="Invalid account details."
>
  <MyTextField label="Name" defaultValue="Devon" />
  <MyTextField
    label="Email"
    defaultValue="devon@example.com"
  />
</FieldGroup>
import {TextFieldContext} from 'react-aria-components';
import {useId} from 'react-aria';

interface FieldGroupProps {
  title?: string;
  children?:
    React.ReactNode;
  errorMessage?: string;
}

function FieldGroup(
  {
    title,
    children,
    errorMessage
  }: FieldGroupProps
) {
  let errorId = useId();
  return (
    <fieldset>
      <legend>
        {title}
      </legend>
      <TextFieldContext.Provider
        value={{
          isInvalid:
            !!errorMessage,
          'aria-describedby':
            errorMessage
              ? errorId
              : undefined
        }}
      >        {children}
      </TextFieldContext.Provider>
      {errorMessage && (
        <small
          id={errorId}
          className="invalid"
        >
          {errorMessage}
        </small>
      )}
    </fieldset>
  );
}

<FieldGroup
  title="Account details"
  errorMessage="Invalid account details."
>
  <MyTextField
    label="Name"
    defaultValue="Devon"
  />
  <MyTextField
    label="Email"
    defaultValue="devon@example.com"
  />
</FieldGroup>
Show CSS
fieldset {
  padding: 1.5em;
  width: fit-content;
}

.invalid {
  color: var(--spectrum-global-color-red-600);
  margin-top: 1em;
  display: block;
}

@media (forced-colors: active) {
  .invalid {
    color: LinkText;
  }
}
fieldset {
  padding: 1.5em;
  width: fit-content;
}

.invalid {
  color: var(--spectrum-global-color-red-600);
  margin-top: 1em;
  display: block;
}

@media (forced-colors: active) {
  .invalid {
    color: LinkText;
  }
}
fieldset {
  padding: 1.5em;
  width: fit-content;
}

.invalid {
  color: var(--spectrum-global-color-red-600);
  margin-top: 1em;
  display: block;
}

@media (forced-colors: active) {
  .invalid {
    color: LinkText;
  }
}

Custom children#

TextField passes props to its child components, such as the label and input, via their associated contexts. These contexts are exported so you can also consume them in your own custom components. This enables you to reuse existing components from your app or component library together with React Aria Components.

ComponentContextPropsRef
LabelLabelContextLabelPropsHTMLLabelElement
InputInputContextInputPropsHTMLInputElement
TextAreaTextAreaContextTextAreaPropsHTMLTextAreaElement
TextTextContextTextPropsHTMLElement

This example consumes from LabelContext in an existing styled label component to make it compatible with React Aria Components. The useContextProps hook merges the local props and ref with the ones provided via context by TextField.

import type {LabelProps} from 'react-aria-components';
import {LabelContext, useContextProps} from 'react-aria-components';

const MyCustomLabel = React.forwardRef(
  (props: LabelProps, ref: React.ForwardedRef<HTMLLabelElement>) => {
    // Merge the local props and ref with the ones provided via context.
    [props, ref] = useContextProps(props, ref, LabelContext);
    // ... your existing Label component
    return <label {...props} ref={ref} />;
  }
);
import type {LabelProps} from 'react-aria-components';
import {
  LabelContext,
  useContextProps
} from 'react-aria-components';

const MyCustomLabel = React.forwardRef(
  (
    props: LabelProps,
    ref: React.ForwardedRef<HTMLLabelElement>
  ) => {
    // Merge the local props and ref with the ones provided via context.
    [props, ref] = useContextProps(
      props,
      ref,
      LabelContext
    );
    // ... your existing Label component
    return <label {...props} ref={ref} />;
  }
);
import type {LabelProps} from 'react-aria-components';
import {
  LabelContext,
  useContextProps
} from 'react-aria-components';

const MyCustomLabel =
  React.forwardRef(
    (
      props: LabelProps,
      ref:
        React.ForwardedRef<
          HTMLLabelElement
        >
    ) => {
      // Merge the local props and ref with the ones provided via context.
      [props, ref] =
        useContextProps(
          props,
          ref,
          LabelContext
        );
      // ... your existing Label component
      return (
        <label
          {...props}
          ref={ref}
        />
      );
    }
  );

Now you can use MyCustomLabel within a TextField, in place of the builtin React Aria Components Label.

<TextField>
  <MyCustomLabel>Name</MyCustomLabel>  <Input />
</TextField>
<TextField>
  <MyCustomLabel>Name</MyCustomLabel>  <Input />
</TextField>
<TextField>
  <MyCustomLabel>
    Name
  </MyCustomLabel>  <Input />
</TextField>

Hooks#

If you need to customize things even further, such as accessing internal state or intercepting events, you can drop down to the lower level Hook-based API. See useTextField for more details.