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.
import { createTextField } from 'material';
const textField = createTextField({ label: 'Name', name: 'name' });
textField.on('change', ({ value }) => save(value));
document.body.append(textField.element);
<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>
import { TextField } from 'material/react';
import { save } from './app';
export function Example() {
return (
<TextField onChange={(event) => save(event.detail.value)} name="name" label="Name" />
);
}
<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>
<script lang="ts">
import { TextField } from 'material/svelte';
import { save } from './app';
</script>
<TextField onchange={(event) => save(event.detail.value)} name="name" label="Name" />
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.
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);
}
<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>
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} />
);
}
<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>
<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} />
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.
import { createTextField } from 'material';
const textField = createTextField({ label: 'Bio', maxLength: 160, supportingText: 'A line about you' });
document.body.append(textField.element);
<m-text-field label="Bio" supporting-text="A line about you" maxlength="160"></m-text-field>
import { TextField } from 'material/react';
export function Example() {
return (
<TextField label="Bio" supportingText="A line about you" maxlength={160} />
);
}
<script setup lang="ts">
import { MTextField } from 'material/vue';
</script>
<template>
<MTextField label="Bio" supporting-text="A line about you" :maxlength="160" />
</template>
<script lang="ts">
import { TextField } from 'material/svelte';
</script>
<TextField label="Bio" supportingText="A line about you" maxlength={160} />
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.
import { createTextField } from 'material';
const textField = createTextField({
label: 'Amount',
type: 'number',
prefixText: '$',
suffixText: 'USD',
leadingIcon: labelIcon,
});
document.body.append(textField.element);
<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>
import { TextField } from 'material/react';
import { labelIcon } from './app';
export function Example() {
return (
<TextField label="Amount" type="number" prefixText="$" suffixText="USD" leadingIcon={labelIcon} />
);
}
<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>
<script lang="ts">
import { TextField } from 'material/svelte';
import { labelIcon } from './app';
</script>
<TextField label="Amount" type="number" prefixText="$" suffixText="USD" leadingIcon={labelIcon} />
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
typeInput type; multiline renders a <textarea>
'text' | 'password' | 'email' | 'number' | 'tel' | 'url' | 'search' | 'multiline''text'variantContainer style
'filled' | 'outlined''filled'densityField height: 56dp, or 40dp when compact (step -4 on the --mtrl-density scale; type and 24dp icons stay unchanged)
'default' | 'compact''default'labelThe floating label
stringundefinednameThe input's name, for forms
stringundefinedvalueInitial value
string''placeholderPlaceholder text; a single space when omitted, so the CSS can tell an empty field
string' 'requiredThe input's required
booleanfalsedisabledRenders the field non-interactive
booleanfalsereadonlyThe input's readonly
booleanfalsemaxLengthThe input's maxlength, and a character counter
numberundefinedpatternThe input's validation pattern
stringundefinedautocompleteThe input's autocomplete token
stringundefinedinputModeThe input's inputmode virtual-keyboard hint (<m-text-field inputmode>)
'none' | 'text' | 'decimal' | 'numeric' | 'tel' | 'search' | 'email' | 'url'undefinedenterKeyHintThe input's enterkeyhint key label (<m-text-field enterkeyhint>)
'enter' | 'done' | 'go' | 'next' | 'previous' | 'search' | 'send'undefinedleadingIconHTML, usually an SVG, before the input
stringundefinedtrailingIconHTML after the input
stringundefinedtrailingIconLabelMakes the trailing icon a button with this accessible name, emitting trailing when activated; without it the icon is decorative
stringundefinedprefixTextStatic text before the value
stringundefinedsuffixTextStatic text after the value
stringundefinedsupportingTextHelper text under the field
stringundefinederrorThe error state
booleanfalseclassExtra CSS classes on the root
stringundefinedprefixPrefix for CSS class names
string'mtrl'Properties
elementThe root: the field, then the supporting text row
HTMLElementfieldThe 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
HTMLElementinputThe native control
HTMLInputElement | HTMLTextAreaElementleadingIcon / trailingIconThe icon elements, when they exist
HTMLElement | nullsupportingTextElementThe supporting text on screen, when there is one
HTMLElement | nullprefixTextElement / suffixTextElementThe affix elements, when they exist
HTMLElement | nullMethods
Value and attributes
getValue() / setValue(value)The input's value; setting it refreshes the empty state
value: stringstring / TextFieldComponentsetAttribute(name, value) / getAttribute(name) / removeAttribute(name)An attribute of the input
name: string, value: stringTextFieldComponent / string | nullAppearance
setVariant(variant) / getVariant()The container style
variant: 'filled' | 'outlined'TextFieldComponent / 'filled' | 'outlined'setDensity(density) / getDensity()The field height
density: 'default' | 'compact'TextFieldComponent / stringsetLabel(text) / getLabel()The floating label
text: stringTextFieldComponent / stringIcons and affixes
setLeadingIcon(html) / removeLeadingIcon()The leading icon
html: stringTextFieldComponentsetTrailingIcon(html, label?) / removeTrailingIcon()The trailing icon; label makes it a button with that accessible name
html: string, label?: stringTextFieldComponentsetPrefixText(text) / removePrefixText()The prefix text
text: stringTextFieldComponentsetSuffixText(text) / removeSuffixText()The suffix text
text: stringTextFieldComponentupdatePositions()Recomputes the label and input padding, after you change the surroundings yourself; the setters above do it
TextFieldComponentSupporting text and errors
setSupportingText(text, isError?) / removeSupportingText()The helper text, optionally in the error style
text: string, isError?: booleanTextFieldComponentsetError(error, message?)The error state, with an optional message in place of the helper text
error: boolean, message?: stringTextFieldComponentisError()Whether the field is in error
booleanState, events and lifecycle
enable() / disable()The disabled state
TextFieldComponenton(event, handler) / off(event, handler)Adds or removes a listener
event: string, handler: FunctionTextFieldComponentdestroy()Tears the component down and releases listeners
voidEvents
inputThe value changed as the user types, or the browser autofilled it
{ value, isEmpty, isAutofilled }changeThe value was committed
{ value, isEmpty, isAutofilled }focus / blurThe input took or lost focus
{ 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 |