score:66

Accepted answer

For most use cases, you should use TextField rather than the lower-level components that it delegates to (such as Input).

The relevant part of the documentation is here.

Particularly this line:

TextField is composed of smaller components ( FormControl, Input, FilledInput, InputLabel, OutlinedInput, and FormHelperText ) that you can leverage directly to significantly customize your form inputs.

The main reason to use these lower-level components is if you need to customize your form input in some way that isn't supported using TextField.

score:12

This is a simplified definition of the TextField component:

<FormControl {...other}>
  {label && (
    <InputLabel {...InputLabelProps}>
      {label}
    </InputLabel>
  )}

  {select ? (
    <Select {...SelectProps}>
      {children}
    </Select>
  ) : (
    <Input {...InputProps} />
  )}

  {helperText && (
    <FormHelperText {...FormHelperTextProps}>
      {helperText}
    </FormHelperText>
  )}
</FormControl>

As you can see, the TextField is more than an Input, it consists of:

  • FormControl: It's just a context provider that is used to pass the TextField state (focus, error, hover...) down to the children and make sure they stay consistent. You usually don't have to use this component directly.

  • InputLabel: The label of the TextField, Input doesn't have one on its own, so if you want to add a label to your Input, use TextField.

  • FormHelperText: The helper text placed below the Input, used to describe the TextField or display some error message in form validation.

  • Input: The input itself. There are actually 3 input components in different variants: Input, OutlinedInput and FilledInput which can be set by the variant prop in TextField. This is one more reason to use TextField, instead of finding and importing different input components, you can just set the variant prop and TextField will know what to render.

  • Select: TextField can be either a Select or an Input. Set the select prop to change the input type to select.

So when to use TextField? In a form where you want to display an Input with a label and have a way to set the error message in a clean API, which is most of the time.

When to use Input? When you don't need all of the above except something to type in, or when you have a need for extreme customization and the API of TextField is not enough for you.

Codesandbox Demo


Related Query

More Query from same tag