Material ui textfield error

In this tutorial, you'll learn how to integrate Material UI into your React form component with a complete walk-through.

Table of Contents

  1. Introduction
  2. Does Material UI have a Form Component?
  3. Getting Started With Material UI Library
    • Prerequisites
    • Creating a React App
    • Installing Material UI
    • Material UI Form Example
  4. React Form Components By MUI
    • TextField
    • Date input
    • Form Group
    • Checkbox
    • FormLabel
  5. material ui form · Content Editor · Surfer
  6. Material UI Form Validation
  7. Form Submit
  8. Creating a Login and Signup Page Using Material UI Form
    • Login Form
    • Signup Form
    • Displaying the Register and Login Component in App.js
  9. Material UI Form Alternatives
  10. Conclusion

Introduction

Do you want to create a stylish and responsive form for your react application using material UI? Forms are an important way to interact with users on your website.

MUI provides components that you can add to the native React Form to easily style your forms.

In this tutorial, you’ll learn how to integrate Material UI into your React form component. We’ll wrap it up with a complete walk-through by creating a login and registration form that is based on the Material UI library.

Does Material UI have a Form Component?

Material UI does not have a form component out of the box. It does have subcomponents that you can use on React forms.

MUI relies heavily on the native React form component as a parent wrapper. You can then pass the subcomponents as components on the parent div.

Other third-party form libraries, such as Formik and React Hook Form, can be integrated with material UI. If you’d like to see how to implement the MUI form with Formik, be sure to check out the video below.

For this guide, we’ll use the MUI form component with the HTML form tag.

Getting Started With Material UI Library

Material UI is a library that provides ready-made templates that make building with React faster. In a previous article, we discussed using MUI button and Grid component. For this tutorial, we’ll explore Form components provided by material UI.

If you’re using MUI for your React application, CopyCat’s Figma to Material UI builder will help you generate production-ready React components based on your Figma design. This would save you a ton of time so you can focus on implementing the component’s logic.

Prerequisites

To follow along with this guide, you’ll need basic knowledge of JavaScript and React. You also need to have Node.js installed on your machine. This would give you access to the NPM package installer.

Creating a React App

We’ll use the create-react-app installer to bootstrap a new react application. To start, open your terminal and navigate into the folder you’d like to install React.

Once there, run the command below.

npx create-react-app mui-form

After the installation completes, navigate to the folder containing the new React files.

Now proceed to install material UI.

Installing Material UI

To install MUI, run the command below.

npm install @mui/material @emotion/react @emotion/styled

If you’re using yarn.

yarn add @mui/material @emotion/react @emotion/styled

Once the installation completes, open the project with a code editor.

Material UI Form Example

As we earlier mentioned, material UI does not provide a form component that can handle form submission or store form data on a database.

You’ll still need to use the native React form or an external library to handle form submissions.

Here is an example of a form component using Material UI components.

<FormControl>
    <FormLabel>Enter Name</FormLabel>
    <TextField></TextField>
    <Button>Submit</Button>
</FormControl>

Remember you need to import the components from the material UI library before you can use them on your component. Here is the import statement for the components we used above.

import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import { FormControl, FormLabel } from '@mui/material';

The code above will have the following output when you run the dev server.

basic form with material UI

When you click on the submit button, nothing happens in the background. This is because MUI does not handle form submissions. You’d need to wrap the components with a <form> tag. The HTML form tag comes with an onSubmit event handler to access form inputs.

React Form Components By MUI

In Material UI, the form component is made of the TextField, Checkbox, Button, and Radio components. When creating a form in React, you’ll use the HTML form tag as the wrapper to handle the form submission.

Within the form tag, you can use any of the components as input fields on your forms. In this section, we’ll discuss some of the field components provided by React.

TextField

The TextField component is the most widely used component when building a form with material UI. With this component, you can accept user input.

It has props that make it easy to extend the component’s usage. For example, you can use it as a TextField, date picker, multiline text input, etc.

You can also use other props provided by material UI such as the variant, size, and color props to customize the look and feel of your input fields. Let’s see some examples.

Setting Variant

To set the variant, we use the variant prop. Material UI has 2 default variants for the text field: Outlined and Filled. Here is an example code of how it’ll look on the UI.

<FormControl>
    <TextField type="text" variant='outlined' defaultValue="Outlined" />
    <TextField type="text" variant='filled' defaultValue="Filled" />
</FormControl>

The code above will have the following output.

using variant prop

Size Prop

With the size prop, you can add or reduce the size of your input fields. Material UI supports 2 sizes by default: small and normal.

Here is an implementation using the size prop.

<FormControl>
   <TextField type="text" size='small' defaultValue="Small" />
   <TextField type="text" size='normal' defaultValue="Normal" />
</FormControl>

The code above will have the following output on the console.

mui text field sizes

Color Prop

The color prop in Material UI allows you to change the colors of the outlined input field. There are various theme colors available for you to choose from.

Here is an example code of using the TextField component with the color prop.

<FormControl>
   <TextField type="text" color='primary' defaultValue="Primary" />
   <TextField type="text" color='secondary' defaultValue="Secondary" />
   <TextField type="text" color='warning' defaultValue="Warning" />
</FormControl>

And this would output the following on the browser.

material ui color prop

The component’s outline color will change based on the theme color provided in the color prop.

Date input

If you’d like to add a date picker to your form, you can use the type prop in the TextField component to set the field type as date. It’ll add a date field that also includes a datepicker so users can use the calendar widget when filling out the form.

<Textfield type="date"></Textfield>

Here is an example of how it’ll look on the UI.

date field with date picker

date field with date picker

Note: Want to explore a different date picker option, be sure to check our complete guide to using the react-datepicker library.

Form Group

FormGroup is a helpful wrapper component that can be used to group form selection components such as the Checkbox and Switch components.

To use the FormGroup component, you’d need to import it into your react component.

import FormGroup from '@mui/material/FormGroup

Then, in the App component’s render block, you can wrap other MUI form components with the FormGroup component. We’ll see an example of using the FormGroup component in the Checkbox section below.

Checkbox

The Checkbox component is used to add checkboxes in Material UI. It can accept the following props:

  • checked
  • defaultChecked
  • disabled
  • color
  • size

Here is an example code for using the Checkbox component.

<FormGroup>
    <Checkbox defaultChecked color="secondary" />
    <Checkbox color="secondary" />
    <Checkbox disabled color="secondary" />
</FormGroup>

Here is the output from the code above.

FormLabel

The form label component is used to add a visual label about an input component. If you’re using a checkbox component on your form, you can use it to add a name that’ll notify users what the field is to be used for. Here is an example of using the form label.

<form>
  <div>
    <FormLabel>Username</FormLabel>
    <TextField />
  </div>
  <div>
    <FormLabel>Password</FormLabel>
    <TextField />
  </div>
</form>

material ui form · Content Editor · Surfer

In React, you can handle changes to form input elements like text fields, checkboxes, and radio buttons by using the onChange event handler. You can listen for this event and update the component’s state in response, which will cause the component to re-render with the new input value.

We can use this handler to access the details users enter when filling out the registration form. You’ll see how this works later in this guide. For now, here is a basic implementation of the onChange handler.

<TextField label="Your Name" onChange={ (e) => setName() } />

Typically you’ll use the onChange event handler to update the state of the component with the value that’s passed into the form.

Material UI Form Validation

Material UI TextField component has a built-in error prop that you can use to highlight the field with a red outline. This can be useful to notify users about wrong or empty input submissions.

The error prop is a boolean field that when set to true highlights the field with a red outline.

<TextField label="Error State" error={true} />

On the browser, this is how the input field will look.

You can also use the required prop to validate your form. The form will only submit if a value is entered for the required field.

We’ll use both props to validate user input when we create the registration and login forms.

Form Submit

To handle submit events on your React forms, use the onSubmit event handler. Then create a function that’ll be triggered when the form is submitted.

In the example below, we’ll prevent the default browser behavior (refreshing the page on submit).

On the form tag, you’d need to add the onSubmit event handler, then assign a function to the handler.

<form onSubmit={handleSubmit}>
<TextField label="Your message" />
</form>

You’ll need to create the function and define the logic for the function you specified in the onSubmit event handler.

const handleSubmit = (event) => {
      event.preventDefault();
      alert("Form Submitted");
}

The handleSubmit function accepts an event argument. We then prevent the default browser behavior of refreshing a page after a form is submitted using the preventDefault() method.

For this example, we’ll simply alert that the form has been submitted on the browser. In the section below, we’ll use the onSubmit event handler to access the values in the Login and Registration forms we’ll create.

Creating a Login and Signup Page Using Material UI Form

Now you have an idea of how Material UI integrates with forms. Let’s take this a little further and build registration and login pages using form components from Material UI.

To start, let’s create a new folder within the src folder to hold our components. I’ll use components as the name for this folder.

Within the components folder, create 2 new files: Login.jsx and Register.jsx. The folder structure should look similar to the one below.

folder structure

Login Form

Here, we’ll create a form to accept the user’s email and password and then log the details entered on the console.

For this, we’ll be adding some code to the Login.jsx file. Be sure to open the file on your code editor. Once you’ve opened it, add the code below to create the login form.

import React, {useState} from "react";
import { TextField, FormControl, Button } from "@mui/material";
import { Link } from "react-router-dom"

const Login = () => {
    const [email, setEmail] = useState("")
    const [password, setPassword] = useState("")
    const [emailError, setEmailError] = useState(false)
    const [passwordError, setPasswordError] = useState(false)

    const handleSubmit = (event) => {
        event.preventDefault()

        setEmailError(false)
        setPasswordError(false)

        if (email == '') {
            setEmailError(true)
        }
        if (password == '') {
            setPasswordError(true)
        }

        if (email && password) {
            console.log(email, password)
        }
    }
    
    return ( 
        <React.Fragment>
        <form autoComplete="off" onSubmit={handleSubmit}>
            <h2>Login Form</h2>
                <TextField 
                    label="Email"
                    onChange={e => setEmail(e.target.value)}
                    required
                    variant="outlined"
                    color="secondary"
                    type="email"
                    sx={{mb: 3}}
                    fullWidth
                    value={email}
                    error={emailError}
                 />
                 <TextField 
                    label="Password"
                    onChange={e => setPassword(e.target.value)}
                    required
                    variant="outlined"
                    color="secondary"
                    type="password"
                    value={password}
                    error={passwordError}
                    fullWidth
                    sx={{mb: 3}}
                 />
                 <Button variant="outlined" color="secondary" type="submit">Login</Button>
            
        </form>
        <small>Need an account? <Link to="/">Register here</Link></small>
        </React.Fragment>
     );
}

export default Login;

In the code above, we create a Login function-based component that includes two TextField components for the email and password. We also have an MUI button to allow form submissions.

In the handleSubmit function, we implement a validation check to confirm if the user entered a value for the field, if any field is not filled, it’ll set the error prop to true and highlight the field with a red outline.

mui login form validation

The form will only be submitted after the user has filled out both input components.

Submitted form

We are not storing the data in any database, we’ll simply log the form data on the console.

login form data

Signup Form

Next, we’ll create a component to allow user registration on the react app. For this, open the Register.jsx file on the code editor. Within the component, copy and paste the code snippet below.

import React, {useState} from 'react';
import { TextField, Button, Container, Stack } from '@mui/material';
import { Link } from "react-router-dom"


const RegisterForm = () => {
    const [firstName, setFirstName] = useState('')
    const [lastName, setLastName] = useState('')
    const [email, setEmail] = useState('')
    const [dateOfBirth, setDateOfBirth] = useState('')
    const [password, setPassword] = useState('')

    function handleSubmit(event) {
        event.preventDefault();
        console.log(firstName, lastName, email, dateOfBirth, password) 
    }

    return (
        <React.Fragment>
            <h2>Register Form</h2>
            <form onSubmit={handleSubmit} action={<Link to="/login" />}>
                <Stack spacing={2} direction="row" sx={{marginBottom: 4}}>
                    <TextField
                        type="text"
                        variant='outlined'
                        color='secondary'
                        label="First Name"
                        onChange={e => setFirstName(e.target.value)}
                        value={firstName}
                        fullWidth
                        required
                    />
                    <TextField
                        type="text"
                        variant='outlined'
                        color='secondary'
                        label="Last Name"
                        onChange={e => setLastName(e.target.value)}
                        value={lastName}
                        fullWidth
                        required
                    />
                </Stack>
                <TextField
                    type="email"
                    variant='outlined'
                    color='secondary'
                    label="Email"
                    onChange={e => setEmail(e.target.value)}
                    value={email}
                    fullWidth
                    required
                    sx={{mb: 4}}
                />
                <TextField
                    type="password"
                    variant='outlined'
                    color='secondary'
                    label="Password"
                    onChange={e => setPassword(e.target.value)}
                    value={password}
                    required
                    fullWidth
                    sx={{mb: 4}}
                />
                <TextField
                    type="date"
                    variant='outlined'
                    color='secondary'
                    label="Date of Birth"
                    onChange={e => setDateOfBirth(e.target.value)}
                    value={dateOfBirth}
                    fullWidth
                    required
                    sx={{mb: 4}}
                />
                <Button variant="outlined" color="secondary" type="submit">Register</Button>
            </form>
            <small>Already have an account? <Link to="/login">Login Here</Link></small>
    
        </React.Fragment>
    )
}

export default RegisterForm;

In the code above, we are using the TextField component to create a registration form. The form accepts 5 inputs for the user’s email, date of birth, password, first name, and last name.

registration form

We use the useState hook to set the value and collect the data from the form input fields. For this project, we are only logging the data from the form on the console.

registration form data

Displaying the Register and Login Component in App.js

We’ll use React Router DOM to handle navigation between the Login and Register components. So you’ll need to install it on your machine. To install react-router-dom, run the command below on the project’s terminal window.

npm install react-router-dom

Once the installation completes, open the index.js file and add the following import statement.

import { BrowserRouter } from "react-router-dom";

Next, wrap the App component with the BrowserRouter component. The resulting code should look similar to the one below.

const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

Now, open the App component and add the following import statement to define your routes. Also, import the Register and Login component we created earlier.

import { Route, Routes } from "react-router-dom";
import Login from './components/Login';
import RegisterForm from './components/Register';

Now replace the entire App function component with the code snippet below.

import { AppBar, Toolbar} from '@mui/material';
import { Container } from '@mui/system';
import React from 'react';

import { Route, Routes } from "react-router-dom"
import Login from './components/Login';
import RegisterForm from './components/Register';

function App() {
  return (
    <React.Fragment>
    <AppBar position='inline'><Toolbar>MUI Form</Toolbar></AppBar>
    <Container>
    <Routes>
      <Route path="/" element={<RegisterForm />} />
      <Route path="/login" element={<Login />} />
    </Routes>
  
    
    </Container>
    </React.Fragment>
  );
}

export default App;

In the code above, we use react-router-dom to create a navigation system for the Login and Register component. We’ll use the Registration Form as the default home page.

We are using the AppBar component to add a navigation bar. Nothing fancy, just to make the project a bit beautiful :).

For this project, we are not interested in implementing complex logic. We are mainly concerned with how the form will look on the UI.

If you’d like to learn more advanced techniques for validating your forms, be sure to check out the video below.

Material UI Form Alternatives

Some alternatives to Material-UI for creating forms in React include:

  1. Ant Design: A popular React UI library that includes a wide range of components, including form components such as Form and Input.
  2. Semantic UI React: A React-based UI library that uses human-friendly HTML to create responsive and customizable user interfaces, including form elements such as Form and Input.
  3. Formik: A popular form management library for React that provides a simple and intuitive API for handling form state, validation, and submission.
  4. React Final Form: A high-performance form library for React that uses the Observer pattern to optimize performance and minimize unnecessary updates.

You can combine some of them with MUI forms to create a custom solution for your forms.

Conclusion

Most modern web applications usually have forms for collecting input from users. It has numerous use cases such as creating registration, login, newsletter, or contact forms.

In this guide, we’ve shown you how to use the Form components provided by material UI. We also showed you a practical use case for these components by building a registration and login form.

If you’d like to access the complete code for the project in this tutorial, you can find it on my GitHub profile.

At CopyCat, we help you build User Interfaces faster than your competitors by providing tools that’ll easily convert your Figma designs into functional react components. If you are a React developer, you can get started with CopyCat today and access CopyCat’s Figma developer plugin.

Text Field (Текстовое поле)

Текстовые поля позволяют пользователям вводить и редактировать текст.

Текстовые поля позволяют пользователям вводить текст в интерфейсе. Обычно они появляются в формах и диалогах.

  • Обратная связь
  • Размер пакета
  • Material Design
  • Figma
  • Adobe
  • Sketch

TextField

TextField представляет собой полноценный элемент управления формы, включая метку (label), само поле ввода и вспомогательный текст.

It supports standard, outlined and filled styling.

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

Note: The standard variant of the TextField is no longer documented in the Material Design guidelines (here’s why), but Material-UI will continue to support it.

Form props

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.

Validation

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

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 rowsMin and rowsMax props to bound it.

Select (Список)

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

Select

Please select your currency

Native select

Please select your currency

Select

Please select your currency

Native select

Please select your currency

Select

Please select your currency

Native select

Please select your currency

Иконки

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

Украшения поля ввода (Input)

The main way is with an InputAdornment. Например, вы можете использовать кнопку-иконку, чтобы скрыть или показать пароль. This can be used to add a prefix, a suffix or an action to an input.

Размеры

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"
/>

Расположение

dense and normal alter other styles to meet the specification. margin prop can be used to alter the vertical spacing of inputs. Using none (default) will not apply margins to the FormControl, whereas dense and normal will.

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

Normal

Some important text

Normal

Some important text

Normal

Some important text

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"
/>

Компоненты

TextField состоит из более мелких компонентов ( FormControl, Input, FilledInput, InputLabel, OutlinedInput, и FormHelperText ) которые вы можете использовать напрямую, чтобы значительно кастомизировать ваши поля ввода.

Вы также могли заметить, что некоторые нативные свойства ввода HTML отсутствуют в компоненте TextField. Это сделано специально. Компонент включает в себя наиболее часто используемые свойства, а для расширенного использования можно использовать базовый компонент, показанный в следующей демонстрации. Вы все еще можете использовать inputPropsсвойства InputProps, InputLabelProps), если хотите избежать излишнего кода.

Поля ввода

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

Цвет

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

Кастомизированные поля ввода

Ниже находятся примеры кастомизации компонента. You can learn more about this in the overrides documentation page.

Настройка не ограничивается CSS, вы можете использовать композицию для создания пользовательских компонентов и придать вашему приложению уникальный стиль. Ниже приведен пример использования компонента InputBase, вдохновленный Google Maps.

🎨 If you are looking for inspiration, you can check MUI Treasury’s customization examples.

Ограничения

Сжатие

Состояние метки поля ввода (label) «shrink» не всегда корректно. Предполагается, что метка поля ввода уменьшается, как только в поле ввода что-нибудь отображается. В некоторых случаях мы не можем определить состояние «shrink» (числовое поле, поле даты, Stripe input). Вы могли заметить совпадения.

сжатие

Чтобы решить эту проблему, вы можете принудительно изменить состояние метки.

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

или

<InputLabel shrink>Contagem</InputLabel>

Плавающая метка

Плавающий ярлык абсолютно позиционируется, он не повлияет на макет страницы. Необходимо убедиться, что поле ввода больше, чем метка для корректного отображения.

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 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:

Name

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:

Name

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"
/>

Интеграция с сторонними библиотеками текстовых полей

Вы можете использовать сторонние библиотеки для форматирования ввода. Вы должны предоставить пользовательскую реализацию элемента <input> со свойством inputComponent.

В следующем примере используются библиотеки response-text-mask и response-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,
    },
  }}
/>;

Доступность

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="my-input">Адрес электронной почты</InputLabel>
  <Input id="my-input" aria-describedby="my-helper-text" />
  <FormHelperText id="my-helper-text">Мы никогда не распостраним ваш адрес.</FormHelperText>
</FormControl>
  • Если вы используете компонент TextField, вам просто нужно предоставить уникальный id.
  • Если вы составляете компонент:
<FormControl>
  <InputLabel htmlFor="my-input">Адрес электронной почты</InputLabel>
  <Input id="my-input" aria-describedby="my-helper-text" />
  <FormHelperText id="my-helper-text">Мы никогда не распостраним ваш адрес.</FormHelperText>
</FormControl>

Дополнительные проекты

Для более сложных вариантов использования вы можете воспользоваться:

  • mui-rff Bindings for using Material-UI with React Final Form.
  • formik-material-ui: Bindings for using Material-UI with formik.
  • redux-form-material-ui: Bindings for using Material-UI with Redux Form.
  • mui-rff: Bindings for using Material-UI with React Final Form.

I suppose there are a couple of different ways to implement this, but how to implement this properly while maintaining backwards compatibility will be interesting:

Assuming default themes (like images above), I suppose these are our approaches:

Approach (1): Deprecate errorText in favor of helperText, and manage error state through error prop

  1. Add prop error that provides error state to the component
  2. Deprecate errorText and errorStyle props (add a warning when used) but if errorText is provided, then ignore error and continue operating with old behavior
  3. If errorText and helperText are used together, provide a separate warning, but ignore errorText implementation and use helperText instead
/* Example 1.Render helper text as red */
<TextField error={true} helperText="This is helper text" />

/* Example 2. Render helper text as grey */
<TextField error={false} helperText="This is helper text" />

/* Example 3. Provide deprecation warning, ignore `error` prop,
and render the helper text as red for backwards compatibility */
<TextField error={true || false} errorText="This is error text" />

/* Example 4. Provide deprecation warning, but behave like example 1 or 2 */
<TextField
  error={true || false} 
  helperText="This is helper text"
  errorText="This is error text" />

Approach (2): Support errorText and helperText, and manage error state through error prop

This is same as approach (1), but we continue supporting both, perhaps like below:

/* Example 1.Render helper text as red */
<TextField error={true} helperText="This is helper text" />

/* Example 2. Render helper text as grey */
<TextField error={false} helperText="This is helper text" />

/* Example 3. Render the error text as red */
<TextField error={true} errorText="This is error text" />

/* Example 3. Render nothing */
<TextField error={false} errorText="This is error text" />

/* Example 4. No idea... For backwards compatibility, I suppose the `error` prop would
have to be assumed true in this case which is weird */
<TextField errorText="This is error text" />

/* Example 5. Error text will show as red */
<TextField
  error={true} 
  helperText="This is helper text"
  errorText="This is error text" />

/* Example 6. Helper text will show as grey */
<TextField
  error={false} 
  helperText="This is helper text"
  errorText="This is error text" />

/* Example 6. I suppose helperText will show as grey, and `error` prop would be
assumed false */
<TextField
  helperText="This is helper text"
  errorText="This is error text" />

Overall, I think approach 2 can get really weird and might confuse users in the long run. But it does have an interesting ability to be able to control whether helper or error text shows based on error state. For example, your error text might change based on validation rules, but after they clear, the original helper text will show again without you have to reset it.

Next, open up the App.js file located in the src folder. You should see this:

App.js

import React from 'react'; import TextField from '@mui/material/TextField'; import './App.css'; import { Button, Radio, RadioGroup, FormControlLabel, FormControl, FormLabel, FormHelperText, FormGroup, Checkbox, } from '@mui/material'; import { useForm } from "react-hook-form"; const App = () => { const { register, handleSubmit, watch, formState: { errors } } = useForm(); const onSubmit = (data) => console.log(data); console.log(errors); return ( <div className="App__form"> <h1> Material UI with React Hook Form - Validation with Error Messages </h1> <form onSubmit={handleSubmit(onSubmit)}> <TextField id="outlined-basic" name="firstName" label="First Name" variant="outlined" fullWidth {...register("firstName", { required: "First Name is required." })} error={Boolean(errors.firstName)} helperText={errors.firstName?.message} /> <TextField id="outlined-basic" label="Last Name" variant="outlined" fullWidth name="lastName" {...register("lastName", { required: "Last Name is required." })} error={Boolean(errors.lastName)} helperText={errors.lastName?.message} /> <TextField id="outlined-basic" label="E-mail" variant="outlined" fullWidth name="email" {...register("email", { required: "E-mail Address is required." })} error={Boolean(errors.email)} helperText={errors.email?.message} /> {/* Radio button */} <FormControl error={Boolean(errors.gender)} > <FormLabel component="legend"> Choose Your Gender </FormLabel> <RadioGroup row aria-label="gender" name="gender"> <FormControlLabel value="female" control={ <Radio {...register("gender", { required: "Choose your gender" })} /> } label="Female" /> <FormControlLabel value="male" control={ <Radio {...register("gender", { required: "Choose your gender" })} /> } label="Male" /> <FormControlLabel value="other" control={ <Radio {...register("gender", { required: "Choose your gender" })} /> } label="Other" /> </RadioGroup> <FormHelperText style={{color:'#d32f2f'}}>{errors.gender?.message}</FormHelperText> </FormControl> <div className="clearfix"></div> {/* Check box */} <FormGroup error={Boolean(errors.tnc)} style={{ display: "block", marginTop: "17px" }} > <FormControlLabel control={ <Checkbox name="tnc" {...register("tnc", { required: "please aggre our terms and condtions" })} /> } label="I aggree all terms and conditions" /> </FormGroup> <FormHelperText style={{color:'#d32f2f'}}>{errors.tnc?.message}</FormHelperText> <div className="clearfix"></div> <Button variant="contained" color="primary" type="submit" className="btns"> create new account </Button> </form> </div> ) } export default App

Понравилась статья? Поделить с друзьями:
  • Material ui error message
  • Material ui error input
  • Material type missing material is not supported как исправить
  • Matcompas dll error 193
  • Matchescounterror ведьмак 3 как исправить