Saltar al contenido

Text Field (campo de texto)

Los campos de texto permiten a los usuarios ingresar y editar texto.

Text fields allow users to enter text into a UI. Generalmente se encuentran en formularios y diálogos.

Basic TextField

The TextField wrapper component is a complete form control including a label, input, and help text. It comes with three variants: outlined (default), filled, and standard.

<TextField id="outlined-basic" label="Outlined" variant="outlined" />
<TextField id="filled-basic" label="Filled" variant="filled" />
<TextField id="standard-basic" label="Standard" variant="standard" />

Nota: La variante estándar de TextField no esta mas documentada en guía Material Design (Aquí esta el por que), pero Material-UI continuara soportándolo.

Propiedades del Form

Standard form attributes are supported e.g. required, disabled, type, etc. as well as a helperText which is used to give context about a field's input, such as how the input will be used.

Some important text

Some important text

Some important text

Validación

The error prop toggles the error state. The helperText prop can then be used to provide feedback to the user about the error.

Incorrect entry.

Incorrect entry.

Incorrect entry.

Multiline

The multiline prop transforms the text field into a textarea or a TextareaAutosize. Unless the rows prop is set, the height of the text field dynamically matches its content (using TextareaAutosize). You can use the minRows and maxRows props to bound it.

Selección

The select prop makes the text field use the Select component internally.

Please select your currency

Please select your currency

Please select your currency

Please select your currency

Please select your currency

Please select your currency

Iconos

There are multiple ways to display an icon with a text field.

Adornos de campos de texto

The main way is with an InputAdornment. This can be used to add a prefix, a suffix, or an action to an input. This can be used to add a prefix, a suffix or an action to an input.

Kg

Kg

Weight

$

Kg

Kg

Weight

$

Kg

Kg

Weight

$

Tamaños

Fancy smaller inputs? Use the size prop.

The filled variant input height can be further reduced by rendering the label outside of it.

<TextField
  hiddenLabel
  id="filled-hidden-label-small"
  defaultValue="Small"
  variant="filled"
  size="small"
/>
<TextField
  hiddenLabel
  id="filled-hidden-label-normal"
  defaultValue="Normal"
  variant="filled"
/>

Margin

The margin prop can be used to alter the vertical spacing of the text field. Using none (default) doesn't apply margins to the FormControl whereas dense and normal do.

<RedBar />
<TextField label={'margin="none"'} id="margin-none" />
<RedBar />
<TextField label={'margin="dense"'} id="margin-dense" margin="dense" />
<RedBar />
<TextField label={'margin="normal"'} id="margin-normal" margin="normal" />
<RedBar />

Full width

fullWidth can be used to make the input take up the full width of its container.

<TextField fullWidth label={'fullWidth'} id="fullWidth" />

Uncontrolled vs. Controlled

The component can be controlled or uncontrolled.

<TextField
  id="outlined-name"
  label="Name"
  value={name}
  onChange={handleChange}
/>
<TextField
  id="outlined-uncontrolled"
  label="Uncontrolled"
  defaultValue="foo"
/>

Componentes

El componente TextField incluye y usa subcomponentes ( FormControl, Input, FilledInput, InputLabel, OutlinedInput y FormHelperText ) que pueden ser usados directamente para personalizar campos de ingreso de texto de manera sustancial.

Puede que también hayas notado que algunas propiedades nativas de input HTML no están presentes en el componente TextField. Esto es a propósito. The component takes care of the most used properties. Then, it's up to the user to use the underlying component shown in the following demo. Aun así, se puede utilizar inputProps (y las propiedades InputProps e InputLabelProps) para personalizar y evitar el código boilerplate.

Some important helper text

Disabled

Error

Inputs

<Input defaultValue="Hello world" inputProps={ariaLabel} />
<Input placeholder="Placeholder" inputProps={ariaLabel} />
<Input disabled defaultValue="Disabled" inputProps={ariaLabel} />
<Input defaultValue="Error" error inputProps={ariaLabel} />

Color

The color prop changes the highlight color of the text field when focused.

<TextField label="Outlined secondary" color="secondary" focused />
<TextField label="Filled success" variant="filled" color="success" focused />
<TextField
  label="Standard warning"
  variant="standard"
  color="warning"
  focused
/>

Inputs personalizados

Here are some examples of customizing the component. Puedes aprender más sobre esto en la sección Personalizando Componentes de la documentación.

Customization does not stop at CSS. You can use composition to build custom components and give your app a unique feel. A continuación sigue un ejemplo del uso del componente InputBase, inspirado por Google Maps.


🎨 Si buscas un poco de inspiración, puedes visitar MUI Treasury's ejemplos de customizacion.

useFormControl

For advanced customization use cases, a useFormControl() hook is exposed. This hook returns the context value of the parent FormControl component.

API

import { useFormControl } from '@material-ui/core/FormControl';

Regresa

value (object):

  • value.adornedStart (bool): Indicate whether the child Input or Select component has a start adornment.
  • value.setAdornedStart (func): Setter function for adornedStart state value.
  • value.color (string): The theme color is being used, inherited from FormControl color prop .
  • value.disabled (bool): Indicate whether the component is being displayed in a disabled state, inherited from FormControl disabled prop.
  • value.error (bool): Indicate whether the component is being displayed in an error state, inherited from FormControl error prop
  • value.filled (bool): Indicate whether input is filled
  • value.focused (bool): Indicate whether the component and its children are being displayed in a focused state
  • value.fullWidth (bool): Indicate whether the component is taking up the full width of its container, inherited from FormControl fullWidth prop
  • value.hiddenLabel (bool): Indicate whether the label is being hidden, inherited from FormControl hiddenLabel prop
  • value.required (bool): Indicate whether the label is indicating that the input is required input, inherited from the FormControl required prop
  • value.size (string): The size of the component, inherited from the FormControl size prop
  • value.variant (string): The variant is being used by the FormControl component and its children, inherited from FormControl variant prop
  • value.onBlur (func): Should be called when the input is blurred
  • value.onFocus (func): Should be called when the input is focused
  • value.onEmpty (func): Should be called when the input is emptied
  • value.onFilled (func): Should be called when the input is filled

Ejemplo

Helper text

<FormControl sx={{ width: '25ch' }}>
  <OutlinedInput placeholder="Please enter text" />
  <MyFormHelperText />
</FormControl>

Limitaciones

Shrink

El estado "shrink" de la etiqueta del campo de texto no está siempre correcto. La etiqueta debe achicarse al momento que el campo demuestra algun texto. En algunas circunstancias, no se puede determinar el estado "shrink" (campo de números, campo de fecha y hora, campo de Stripe). Tal vez veas una superposición.

shrink

Para resolver el problema, puedes forzar el estado "shrink" de la etiqueta.

<TextField InputLabelProps={{ shrink: true }} />

o

<InputLabel shrink>Contagem</InputLabel>

Floating label

The floating label is absolutely positioned. It won't impact the layout of the page. Make sure that the input is larger than the label to display correctly.

type="number"

Inputs of type="number" have potential usability issues:

  • Allowing certain non-numeric characters ('e', '+', '-', '.') and silently discarding others and silently discarding others and silently discarding others and silently discarding others
  • Si se está componiendo el componente:

and more - see this article by the GOV. UK Design System team for a more detailed explanation.

For number validation, one viable alternative is to use the default input type="text" with the pattern attribute, for example:

<TextField inputProps={{ inputMode: 'numeric', pattern: '[0-9]*' }} />

In the future, we might provide a number input component.

Helper text

The helper text prop affects the height of the text field. If two text fields are placed side by side, one with a helper text and one without, they will have different heights. For example:

Please enter your name

<TextField
  helperText="Please enter your name"
  id="demo-helper-text-misaligned"
  label="Name"
/>
<TextField id="demo-helper-text-misaligned-no-helper" label="Name" />

This can be fixed by passing a space character to the helperText prop:

Please enter your name

<TextField
  helperText="Please enter your name"
  id="demo-helper-text-aligned"
  label="Name"
/>
<TextField
  helperText=" "
  id="demo-helper-text-aligned-no-helper"
  label="Name"
/>

Integration with 3rd party input libraries

Se pueden utilizar librerías externas para formatear un campo de texto. Para ello, hay que proporcionar una implementación personalizada del elemento <input> con el atributo inputComponent.

El siguiente demo utiliza las librerías react-text-mask y react-number-format. The same concept could be applied to e.g. react-stripe-element.

The provided input component should expose a ref with a value that implements the following interface:

interface InputElement {
  focus(): void;
  value?: string;
}
const MyInputComponent = React.forwardRef((props, ref) => {
  const { component: Component, ...other } = props;

  // implement `InputElement` interface
  React.useImperativeHandle(ref, () => ({
    focus: () => {
      // logic to focus the rendered component from 3rd party belongs here
    },
    // hiding the value e.g. react-stripe-elements
  }));

  // `Component` will be your `SomeThirdPartyComponent` from below
  return <Component {...other} />;
});

// usage
<TextField
  InputProps={{
    inputComponent: MyInputComponent,
    inputProps: {
      component: SomeThirdPartyComponent,
    },
  }}
/>;

Accesibilidad

In order for the text field to be accessible, the input should be linked to the label and the helper text. The underlying DOM nodes should have this structure:

<FormControl>
  <InputLabel htmlFor="mi-campo">Email</InputLabel>
  <Input id="mi-campo" aria-describedby="mi-texto-de-ayuda" />
  <FormHelperText id="mi-texto-de-ayuda">Nunca compartiremos tu email.</FormHelperText>
</FormControl>
  • Si se usa el componente TextField, sólo hay que proporcionar un id único.
  • Si se está componiendo el componente:
<FormControl>
  <InputLabel htmlFor="mi-campo">Email</InputLabel>
  <Input id="mi-campo" aria-describedby="mi-texto-de-ayuda" />
  <FormHelperText id="mi-texto-de-ayuda">Nunca compartiremos tu email.</FormHelperText>
</FormControl>

Proyectos relacionados

For more advanced use cases, you might be able to take advantage of: