Material UI Forms

How to Create Forms in React Using Material UI Form Component

December 16, 2022
David Ozokoye
React.js

The Fastest Way to Build React UI

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

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.

1
npx create-react-app mui-form

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

1
cd mui-form

Now proceed to install material UI.

Installing Material UI

To install MUI, run the command below.

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

If you’re using yarn.

1
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.

1
2
3
4
5
<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.

1
2
3
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.

1
2
3
4
<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.

1
2
3
4
<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.

1
2
3
4
5
<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.

1
<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.

1
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.

1
2
3
4
5
<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.

1
2
3
4
5
6
7
8
9
10
<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.

1
<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.

1
<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.

1
2
3
<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.

1
2
3
4
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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.

1
npm install react-router-dom

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

1
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.

1
2
3
4
5
6
7
8
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.

1
2
3
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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.

Related Articles

  • React.js

    Understanding and Using Material UI Checkbox Component like a Pro

    https://images.surferseo.art/d51484dd-6d0d-4b95-9f1d-d17058c15ba0.png Introduction Checkboxes are form elements that allow the user to choose one or more options from a list. They're frequently used in web forms to let users select multiple options. Such as multiple items in a shopping cart or…

    December 23, 2022
  • React Best Practices

    How to Convert Figma to React

    Introduction The front-end development ecosystem is continuously evolving and new trends come and go daily. From UX prototyping tools to Web development frameworks, there is a lot of innovation happening. New tools are dropped more frequently than ever, especially in…

    June 9, 2022

Convert Figma To React

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Convert Design to Code