Search
MaterialComponentsDocs
Components overviewApp barBadgeButtonsButton groupButtonExtended FABFAB menuFABIcon buttonSplit buttonCardCarouselCheckboxChipsDate & time pickersDate pickerTime pickerDialogDividerListLoading & progressLoading indicatorProgressMenuNavigationNavigation barNavigation drawerNavigation railRadio buttonsSearchSelectSheetsBottom sheetSide sheetSliderSnackbarSwitchTabsText fieldToolbarTooltip

Text field

Enter text with helpful context. Explore field styles, input types, icons, and validation states.

FactoryWeb ComponentsReactVueSvelteSolidJS
PublishedUpdated

A text field lets people enter free-form text: a name, an email address, a password, a paragraph. Use one whenever the answer can't be picked from a list. It wraps a native <input>, or a <textarea>, in the filled or outlined container, with a label that floats out of the way, and optional icons, affixes and supporting text.

Usage

input fires as the value changes, change when it is committed.

Vanilla
import { createTextField } from 'material';

const textField = createTextField({ label: 'Name', name: 'name' });
textField.on('change', ({ value }) => save(value));
document.body.append(textField.element);
Web Components
<m-text-field name="name" label="Name"></m-text-field>

<script type="module">
  const textField = document.querySelector('m-text-field');
  textField.addEventListener('change', (event) => save(event.detail.value));
</script>
React
import { TextField } from 'material/react';
import { save } from './app';

export function Example() {
  return (
    <TextField onChange={(event) => save(event.detail.value)} name="name" label="Name" />
  );
}
Vue
<script setup lang="ts">
import { MTextField } from 'material/vue';
import { save } from './app';
</script>

<template>
  <MTextField @change="save($event.detail.value)" name="name" label="Name" />
</template>
Svelte
<script lang="ts">
  import { TextField } from 'material/svelte';
  import { save } from './app';
</script>

<TextField onchange={(event) => save(event.detail.value)} name="name" label="Name" />
SolidJS
import { TextField } from 'material/solid';
import { save } from './app';

export function Example() {
  return (
    <TextField onChange={(event) => save(event.detail.value)} name="name" label="Name" />
  );
}

variant is filled (the default) or outlined; density: 'compact' lowers the field from 56 to 40dp. type: 'multiline' renders a <textarea>. Without a width from the page, a text field is 280dp wide; any width you give it, or a stretching layout, wins.

Examples

Supporting text and errors

Supporting text sits under the field and describes it. An action sets the error state: the field and its supporting text take the error colors, and the input gets aria-invalid. setError(true, message) shows a message in place of the supporting text, and setError(false) restores it.

Vanilla
import { createTextField } from 'material';

const textField = createTextField({
  label: 'Email',
  type: 'email',
  variant: 'outlined',
  supportingText: 'We never share it',
});
document.body.append(textField.element);

function invalid() {
  textField.setSupportingText('Enter a valid email address');
  textField.setError(true);
}
Web Components
<m-text-field variant="outlined" label="Email" type="email" supporting-text="We never share it"></m-text-field>

<script type="module">
  const textField = document.querySelector('m-text-field');

  function invalid() {
    textField.setAttribute('supporting-text', "Enter a valid email address");
    textField.toggleAttribute('error', true);
  }
</script>
React
import { useState } from 'react';
import { TextField } from 'material/react';

export function Example() {
  const [supportingText, setSupportingText] = useState("We never share it");
  const [error, setError] = useState(false);
  const invalid = () => {
    setSupportingText("Enter a valid email address");
    setError(true);
  };

  return (
    <TextField variant="outlined" label="Email" type="email" supportingText={supportingText} error={error} />
  );
}
Vue
<script setup lang="ts">
import { ref } from 'vue';
import { MTextField } from 'material/vue';

const supportingText = ref("We never share it");
const error = ref(false);

function invalid() {
  supportingText.value = "Enter a valid email address";
  error.value = true;
}
</script>

<template>
  <MTextField variant="outlined" label="Email" type="email" :supporting-text="supportingText" :error="error" />
</template>
Svelte
<script lang="ts">
  import { TextField } from 'material/svelte';

  let supportingText = $state("We never share it");
  let error = $state(false);

  function invalid() {
    supportingText = "Enter a valid email address";
    error = true;
  }
</script>

<TextField variant="outlined" label="Email" type="email" supportingText={supportingText} error={error} />
SolidJS
import { createSignal } from 'solid-js';
import { TextField } from 'material/solid';

export function Example() {
  const [supportingText, setSupportingText] = createSignal("We never share it");
  const [error, setError] = createSignal(false);
  const invalid = () => {
    setSupportingText("Enter a valid email address");
    setError(true);
  };

  return (
    <TextField variant="outlined" label="Email" type="email" supportingText={supportingText()} error={error()} />
  );
}

A character counter

With maxLength, the supporting text row ends with a counter, 0/160, that follows typing and setValue(). A limit set or removed later on the input (<m-text-field maxlength> does this) adds or removes it. It describes the input, so a screen reader hears it with the field, not on every keystroke, and it takes the error color while the field is in error.

Vanilla
import { createTextField } from 'material';

const textField = createTextField({ label: 'Bio', maxLength: 160, supportingText: 'A line about you' });
document.body.append(textField.element);
Web Components
<m-text-field label="Bio" supporting-text="A line about you" maxlength="160"></m-text-field>
React
import { TextField } from 'material/react';

export function Example() {
  return (
    <TextField label="Bio" supportingText="A line about you" maxlength={160} />
  );
}
Vue
<script setup lang="ts">
import { MTextField } from 'material/vue';
</script>

<template>
  <MTextField label="Bio" supporting-text="A line about you" :maxlength="160" />
</template>
Svelte
<script lang="ts">
  import { TextField } from 'material/svelte';
</script>

<TextField label="Bio" supportingText="A line about you" maxlength={160} />
SolidJS
import { TextField } from 'material/solid';

export function Example() {
  return (
    <TextField label="Bio" supportingText="A line about you" maxlength={160} />
  );
}

Affixes and icons

prefixText and suffixText sit beside the value, such as a currency and a unit; leadingIcon and trailingIcon take SVG markup. Their setters create the slot when the field was built without it.

Vanilla
import { createTextField } from 'material';

const textField = createTextField({
  label: 'Amount',
  type: 'number',
  prefixText: '$',
  suffixText: 'USD',
  leadingIcon: labelIcon,
});
document.body.append(textField.element);
Web Components
<m-text-field label="Amount" type="number" prefix-text="$" suffix-text="USD"></m-text-field>

<script type="module">
  const textField = document.querySelector('m-text-field');
  textField.setAttribute('leading-icon', labelIcon);
</script>
React
import { TextField } from 'material/react';
import { labelIcon } from './app';

export function Example() {
  return (
    <TextField label="Amount" type="number" prefixText="$" suffixText="USD" leadingIcon={labelIcon} />
  );
}
Vue
<script setup lang="ts">
import { MTextField } from 'material/vue';
import { labelIcon } from './app';
</script>

<template>
  <MTextField label="Amount" type="number" prefix-text="$" suffix-text="USD" :leading-icon="labelIcon" />
</template>
Svelte
<script lang="ts">
  import { TextField } from 'material/svelte';
  import { labelIcon } from './app';
</script>

<TextField label="Amount" type="number" prefixText="$" suffixText="USD" leadingIcon={labelIcon} />
SolidJS
import { TextField } from 'material/solid';
import { labelIcon } from './app';

export function Example() {
  return (
    <TextField label="Amount" type="number" prefixText="$" suffixText="USD" leadingIcon={labelIcon} />
  );
}

A password field with a reveal button, and validating an email as it is left, are planned for Showcase.

API

Options

type

Input type; multiline renders a <textarea>

Type'text' | 'password' | 'email' | 'number' | 'tel' | 'url' | 'search' | 'multiline'
Default'text'
variant

Container style

Type'filled' | 'outlined'
Default'filled'
density

Field height: 56dp, or 40dp when compact (step -4 on the --mtrl-density scale; type and 24dp icons stay unchanged)

Type'default' | 'compact'
Default'default'
label

The floating label

Typestring
Defaultundefined
name

The input's name, for forms

Typestring
Defaultundefined
value

Initial value

Typestring
Default''
placeholder

Placeholder text; a single space when omitted, so the CSS can tell an empty field

Typestring
Default' '
required

The input's required

Typeboolean
Defaultfalse
disabled

Renders the field non-interactive

Typeboolean
Defaultfalse
readonly

The input's readonly

Typeboolean
Defaultfalse
maxLength

The input's maxlength, and a character counter

Typenumber
Defaultundefined
pattern

The input's validation pattern

Typestring
Defaultundefined
autocomplete

The input's autocomplete token

Typestring
Defaultundefined
inputMode

The input's inputmode virtual-keyboard hint (<m-text-field inputmode>)

Type'none' | 'text' | 'decimal' | 'numeric' | 'tel' | 'search' | 'email' | 'url'
Defaultundefined
enterKeyHint

The input's enterkeyhint key label (<m-text-field enterkeyhint>)

Type'enter' | 'done' | 'go' | 'next' | 'previous' | 'search' | 'send'
Defaultundefined
leadingIcon

HTML, usually an SVG, before the input

Typestring
Defaultundefined
trailingIcon

HTML after the input

Typestring
Defaultundefined
trailingIconLabel

Makes the trailing icon a button with this accessible name, emitting trailing when activated; without it the icon is decorative

Typestring
Defaultundefined
prefixText

Static text before the value

Typestring
Defaultundefined
suffixText

Static text after the value

Typestring
Defaultundefined
supportingText

Helper text under the field

Typestring
Defaultundefined
error

The error state

Typeboolean
Defaultfalse
class

Extra CSS classes on the root

Typestring
Defaultundefined
prefix

Prefix for CSS class names

Typestring
Default'mtrl'

Properties

element

The root: the field, then the supporting text row

TypeHTMLElement
field

The container under the root: label, input, outline, icons and affixes. Anchor popovers to it, not to the root, so the supporting text row never pushes them down

TypeHTMLElement
input

The native control

TypeHTMLInputElement | HTMLTextAreaElement
leadingIcon / trailingIcon

The icon elements, when they exist

TypeHTMLElement | null
supportingTextElement

The supporting text on screen, when there is one

TypeHTMLElement | null
prefixTextElement / suffixTextElement

The affix elements, when they exist

TypeHTMLElement | null

Methods

Value and attributes

getValue() / setValue(value)

The input's value; setting it refreshes the empty state

Parametersvalue: string
Returnsstring / TextFieldComponent
setAttribute(name, value) / getAttribute(name) / removeAttribute(name)

An attribute of the input

Parametersname: string, value: string
ReturnsTextFieldComponent / string | null

Appearance

setVariant(variant) / getVariant()

The container style

Parametersvariant: 'filled' | 'outlined'
ReturnsTextFieldComponent / 'filled' | 'outlined'
setDensity(density) / getDensity()

The field height

Parametersdensity: 'default' | 'compact'
ReturnsTextFieldComponent / string
setLabel(text) / getLabel()

The floating label

Parameterstext: string
ReturnsTextFieldComponent / string

Icons and affixes

setLeadingIcon(html) / removeLeadingIcon()

The leading icon

Parametershtml: string
ReturnsTextFieldComponent
setTrailingIcon(html, label?) / removeTrailingIcon()

The trailing icon; label makes it a button with that accessible name

Parametershtml: string, label?: string
ReturnsTextFieldComponent
setPrefixText(text) / removePrefixText()

The prefix text

Parameterstext: string
ReturnsTextFieldComponent
setSuffixText(text) / removeSuffixText()

The suffix text

Parameterstext: string
ReturnsTextFieldComponent
updatePositions()

Recomputes the label and input padding, after you change the surroundings yourself; the setters above do it

Parametersnone
ReturnsTextFieldComponent

Supporting text and errors

setSupportingText(text, isError?) / removeSupportingText()

The helper text, optionally in the error style

Parameterstext: string, isError?: boolean
ReturnsTextFieldComponent
setError(error, message?)

The error state, with an optional message in place of the helper text

Parameterserror: boolean, message?: string
ReturnsTextFieldComponent
isError()

Whether the field is in error

Parametersnone
Returnsboolean

State, events and lifecycle

enable() / disable()

The disabled state

Parametersnone
ReturnsTextFieldComponent
on(event, handler) / off(event, handler)

Adds or removes a listener

Parametersevent: string, handler: Function
ReturnsTextFieldComponent
destroy()

Tears the component down and releases listeners

Parametersnone
Returnsvoid

Events

input

The value changed as the user types, or the browser autofilled it

Payload{ value, isEmpty, isAutofilled }
change

The value was committed

Payload{ value, isEmpty, isAutofilled }
focus / blur

The input took or lost focus

Payload{ isEmpty }

Autofill fires no keystrokes: it is detected and emitted as input with isAutofilled: true. The web component's input and change carry { value }.

Styling

The root holds two children: the field, then the supporting text row, which exists only while it holds a helper or a counter.

.mtrl-text-field                root (element)
├─ .mtrl-text-field__field      the container (field): label, input, outline, icons, affixes
└─ .mtrl-text-field__supporting the row under it, in the flow
   ├─ .mtrl-text-field__helper  start
   └─ .mtrl-text-field__counter end

The row is in the flow: a helper that wraps pushes what follows down, and a field without one is 56dp tall. Since mtrl 0.10 the label, input and slots are inside __field, not direct children of the root: CSS written as .mtrl-text-field > .mtrl-text-field__input now goes through the field, .mtrl-text-field__field > …. The filled indicator is .mtrl-text-field__field::before.

.mtrl-text-field { }
.mtrl-text-field--filled, .mtrl-text-field--outlined { }
.mtrl-text-field--density-compact, .mtrl-text-field--multiline { }
.mtrl-text-field--focused, .mtrl-text-field--empty, .mtrl-text-field--error, .mtrl-text-field--disabled { }
.mtrl-text-field__field, .mtrl-text-field__input, .mtrl-text-field__label { }
.mtrl-text-field__leading-icon, .mtrl-text-field__trailing-icon { }
.mtrl-text-field__prefix, .mtrl-text-field__suffix { }
.mtrl-text-field__supporting, .mtrl-text-field__helper, .mtrl-text-field__helper--error { }
.mtrl-text-field__counter { }
.mtrl-text-field__outline, .mtrl-text-field__outline--notched { }

The label has no --floating class: it rises with the root's --focused and --empty classes and the input's own state. The outlined border is an __outline of three segments (__outline-leading, __outline-notch, __outline-trailing), whose notch is sized from the label and opened by __outline--notched. The icon inset is in the stylesheet. An affix's width is measured into --mtrl-text-field-prefix-width and --mtrl-text-field-suffix-width, which is why updatePositions() exists.

Density (--mtrl-density or density: 'compact', the scale's fourth step) changes a container's height, never its type or its icons. The text field's compact option therefore keeps Body Large and 24dp icons. A page that wants the old smaller compact text can apply it in CSS:

.mtrl-text-field--density-compact .mtrl-text-field__input,
.mtrl-text-field--density-compact .mtrl-text-field__label,
.mtrl-text-field--density-compact .mtrl-text-field__prefix,
.mtrl-text-field--density-compact .mtrl-text-field__suffix {
  font-family: var(--mtrl-sys-typescale-body-medium-font);
  font-size: var(--mtrl-sys-typescale-body-medium-font-size);
  line-height: var(--mtrl-sys-typescale-body-medium-line-height);
  letter-spacing: var(--mtrl-sys-typescale-body-medium-letter-spacing);
  font-weight: var(--mtrl-sys-typescale-body-medium-font-weight);
}

Measurements

From _text-field.scss in material, which names no M3 token for them.

Attribute Value Source
Field height 56dp .mtrl-text-field__input { height }
Field height, compact 40dp --density-compact (--mtrl-density: -4)
Container corner 4dp f.get-shape('extra-small')
Filled corner 4dp, top only the filled variant's border-radius
Input padding 13dp 16dp .mtrl-text-field__input { padding }
Filled input padding 24dp 16dp 7dp the filled variant's input rule
Icon 24dp the leading and trailing icon rules
Input padding beside an icon 52dp the --with-leading-icon and --with-trailing-icon input rules
Input padding beside an affix 16dp, plus the affix width and 2dp (the width is 32dp until measured) --with-prefix and --with-suffix, beside-affix
Active indicator 1dp at rest, 2dp focused the filled input's border-bottom and .mtrl-text-field__field::before
Input type Body Large m.typography('body-large')
Supporting text type Body Small m.typography('body-small')
Supporting text row 4dp above, 16dp each side TextFieldDefaults.supportingTextPadding
Multiline minimum height 100dp (84dp floor when compact) the --multiline input rule
Width, unsized 280dp Compose TextFieldDefaults.MinWidth