Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

Master Material UI Input Components: An Easy to Follow Guide

Introduction

Are you looking to create a form for your web application and want to learn how Material UI Input components work? Material UI is a frontend web framework that provides building blocks for most parts of a website including input elements.

In this tutorial, we’ll explain how MUI input works and then cover all available input components. We’ll also apply the knowledge we’ve gained by implementing a blog post creation form.

Before we begin, here is a brief introduction to Material UI.

Understanding Material UI Input

As we earlier mentioned, Material UI is a frontend framework that provides ready-made components that make building with React faster. There are components for creating forms, adding icons, and also input components.

Speaking of components and templates, PureCode has a template gallery of over 10,000 AI-generated templates to integrate into your web apps built using Material UI, Tailwind CSS, or vanilla CSS.

Get Started With PureCode

Let’s Start with Material UI

In this section, we’ll be installing React and Material UI on a new project. If you already have an existing project, skip the React installation part and proceed to install MUI.

Prerequisites

To follow along with this guide:

  • You’ll need basic knowledge of JavaScript and React.

  • You’ll also need to have Node.js installed on your machine. This would give you access to the NPM package installer.

If you need a refresher with React, check out the video below.

Installing React and Material UI Core

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

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

cd mui-input

Now proceed to install 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 is completed, open the project with your preferred code editor.

Basic Configuration and Integration

Material UI has many input components. The most commonly used ones are the Input and TextField components. Each of them can accept different props to control how they appear.

To use an input component, you’ll first need to import it into your project.

import Input from '@mui/material/Input';

Once you’ve imported it into your project, you can add it as a component to your web page by simply calling the component.

<Input />

Running the development server will display a basic input element on the frontend.

Input element example

All material UI input components accept props. Props are used to define properties for the component. Using the Input component doesn’t provide many customization options. We recommend using the TextField component instead.

Exploring Material UI Input Components

Material UI comes with many text field components, each with unique features and use cases. Let’s explore some of the key components:

TextField

The TextField component is the most widely used component for creating standard text inputs. It offers various props to customize its appearance and behavior, making it versatile for various input scenarios.

Example code:

<TextField
      label="Text Input"
      variant="outlined"
      fullWidth
 />
TextField example with floating label

OutlinedInput

The OutlinedInput component is perfect for creating inputs with stylish outlined borders. This component is a great choice if you want your form to have a modern look.

Example code:

<OutlinedInput
   placeholder="Outlined Input"
   fullWidth
 />
Outlined text field

The fullWidth prop ensures the field occupies the width of its container. If you use the outlined input component, you won’t be able to apply the variant prop to your input elements.

FilledInput

FilledInput provides input fields with a filled background. It’s a visually appealing way to capture user input while maintaining a clean design. Here is an example:

<FilledInput
      placeholder="Filled Input"
      fullWidth
      color="success"
/>

We use the fullWidth prop to ensure the text field spans the width of its container. The color prop specifies the color for the text field. The placeholder prop sets the input placeholder string text.

Full width filled button

InputBase

InputBase acts as a foundational component for creating custom inputs. It allows you to build your input from scratch and is often used for more specialized input requirements.

<InputBase
      placeholder="Custom Input"
/>
Enter and edit text in a custom input component

Input Component Props

For this section, we’ll cover the most common props you’ll likely use with the text field component

Label

Each input element can have a label. The label describes the details the text field will accept. You can add a label using the label prop. Once you add it, you’ll need to define the label as a string text.

<TextField label="Text Field label" />

You can also customize input labels by using CSS-in-JS (JSS) within your component or by applying classes to the InputLabel component. This allows you to adjust the label’s typography, color, and positioning.

<TextField
  label="Your Name"
  InputLabelProps={{
    style: {
      color: 'green',
      top: '-5px',
    },
  }}
/>
Customizing The label of text fields

Color

Material UI provides props to update the colors of input elements to use default theme colors. Below is the list of colors MUI supports by default:

  • Primary

  • Secondary

  • Info

  • Error

  • Success

  • Warning

Here is an example of how these theme colors look.

MUI theme color text field examples

Below is the code for the example above.

<Stack direction="row" spacing={2}>
      <TextField
      label=" Primary"
      variant="outlined"
      color="primary" 
      />
      <TextField
      label=" Secondary"
      variant="outlined"
      color="secondary"
    />
      <TextField
      label="Info"
      variant="outlined"
      color="info"
    />
      <TextField
      label="Error"
      variant="outlined"
      color="error"
    />
      <TextField
      label="Success"
      variant="outlined"
      color="success"
    />
      <TextField
      label="Warning"
      variant="outlined"
      color="warning"
    />
</Stack>

We use the Stack component and set its direction to row. This makes the text fields display side by side. The number of rows determines the width of the container.

Size

Material UI components support 2 sizes by default: Small and Normal. The Normal size is the default size for all input elements MUI supports. Here is how they look:

<TextField
      label="Small"
      variant="outlined"
      size="small"
      />
      <TextField
      label="Normal"
      variant="outlined"
      size="normal"
/>
Material UI text field sizes

Variants

Material UI Input fields have 3 variants. Standard, Filled, and Outlined. The standard variant is the default variant which will be used if you don’t specify a variant for the text field. Here is an example showing all the available variants.

<TextField label="Outlined" variant="outlined" />
<TextField label="Filled" variant="filled" />
<TextField label="Standard" variant="standard" />
text field variants

Advanced Input Features

Material UI Input components offer advanced features that can significantly improve your forms and user experience:

Adding Icons and Helper Text to Inputs

Enhance your inputs with icons and helper text to provide additional context to users. You can include icons within the input field using the InputProps property and the startAdornment and endAdornment properties.

Here is an example implementation of a search field with a search icon. Start by importing the TextField and InputAdornment components from material UI.

import TextField from '@mui/material/TextField';
import InputAdornment from '@mui/material/InputAdornment';
import SearchIcon from '@mui/icons-material/Search';

Then in the component, add the code snippet below:

<TextField
  label="Search"
  sx={{my: 3}}
  InputProps={{
    startAdornment: (
      <InputAdornment position="start">
        <SearchIcon />
      </InputAdornment>
    ),
  }}
/>

Here is how the code looks in the frontend.

Search field with Search icon

Controlling Input Value and State

You can manage the value and state of your input components by controlling them through React’s useState and onChange event handlers. This gives you full control over input values and how they interact with your application’s state.

import React, { useState } from 'react;
import TextField from '@mui/material/TextField';

const [inputValue, setInputValue] = useState('');

const handleInputChange = (e) => {
  setInputValue(e.target.value);
  console.log(inputValue)
};

<TextField
  label="Name"
  value={inputValue}
  onChange={handleInputChange}
/>

For this example, we use React’s useState hook to store the state of the field. The handleInputChange function contains the logic for when the user starts to type. We are only setting the state and logging the value for this example.

Whenever the user starts to type into the text field, the value automatically updates in the state variable.

Text field example with form handling

You’ll also see the text field value logged in the console.

text field value logged in the console

Implementing Input Masking and Formatting

For advanced scenarios like input masking and formatting, you can use 3rd-party libraries like react-text-mask to improve user experience. These libraries allow you to define custom input patterns and formatting rules.

To use the react input mask library, you’ll first need to install it on your project. For this, run the command below.

npm install react-input-mask

After that, you’ll need to import the InputMask component from the react-input-mask library and use it in your React component to create a masked input field. Let’s create a phone number input field with a format of (123) 456-7890:

First, copy and paste the code below to your component.

import React from 'react';
import TextField from '@mui/material/TextField';
import InputMask from 'react-input-mask';

function PhoneInput() {
  const handlePhoneNumberChange = (e) => {
    console.log(e.target.value); // You can access the raw, unmasked value here
  };

  return (
    <div>
      <InputMask
        mask="(999) 999-9999"
        maskChar="_" // You can customize the mask character
        alwaysShowMask // Set to true to always display the mask, even when the input is empty
        onChange={handlePhoneNumberChange}
      >
        {() => (
          <TextField
            label="Phone Number"
            variant="outlined"
            fullWidth
            InputLabelProps={{ shrink: true }}
          />
        )}
      </InputMask>
    </div>
  );
}

export default PhoneInput;

In the code above, the InputMask component wraps the TextField component, ensuring that input masking is applied to the TextField.

The TextField component is created within the InputMask component, and the input masking behavior is applied to the TextField by using the InputMask component’s wrapper function.

Here is how it looks on the frontend.

Input mask field example

Creating a Blog Post Form

Let’s build a Blog Post Form using Material UI TextField components for the fields: Post Title, Post Content, Date Posted, and Post Author.

We’ll implement input handling to store the input in a state and display it in the console. You can use this as a starting point and integrate it into your React application.

Building a Blog Post Form Using Material UI Input Components

Start by creating a new React component for the Blog Post Form, e.g., BlogPostForm.js.

After that, we’ll import React and useState from React. We’ll also import the TextField and Button components from Material UI.

import React, { useState } from 'react';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';

Next, let’s define our BlogPostForm component and set up the initial state to store the input data. For this, copy and paste the code snippet below.

import React, { useState } from 'react';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';

function BlogPostForm() {
  const [formData, setFormData] = useState({
    title: '',
    content: '',
    datePosted: '',
    author: '',
  });

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData); // You can access the input data here
  };

  return (
    <form onSubmit={handleSubmit}>
      <TextField
        name="title"
        label="Post Title"
        variant="outlined"
        sx={{my: 2}}
        fullWidth
        value={formData.title}
        onChange={handleInputChange}
      />
      <TextField
        name="content"
        label="Post Content"
        multiline
        rows={4}
        sx={{my: 2}}
        variant="outlined"
        fullWidth
        value={formData.content}
        onChange={handleInputChange}
      />
      <TextField
        name="datePosted"
        label="Date Posted"
        type="datetime-local"
        variant="outlined"
        sx={{my: 2}}
        fullWidth
        value={formData.datePosted}
        onChange={handleInputChange}
      />
      <TextField
        name="author"
        label="Post Author"
        variant="outlined"
        fullWidth
        sx={{my: 2}}
        value={formData.author}
        onChange={handleInputChange}
      />
      <Button type="submit" sx={{my: 2}} variant="contained" fullWidth color="success">Post</Button>
   
    </form>
  );
}

export default BlogPostForm;

In the code above, we create a BlogPostForm functional component and set up the initial state using useState to store the form input data.

The handleInputChange function updates the state when the user enters data in the TextField components.

handleSubmit function is called when the form is submitted and logs the input data to the console.

The TextField components are used for each input field. We provide a name, label, and value prop for each field, and we use the onChange event handler to update the state when the user interacts with the input fields.

For the “Date Posted” field, we use type=”datetime-local” to allow users to use MUI’s datepicker component.

Now, you can include the BlogPostForm component in your application, and it will allow you to input data for a blog post and display it in the console when submitted.

Blog post creation form

Handling Form Validation and Error States

Handling form validation and error states with Material UI’s TextField component is an essential aspect of creating user-friendly forms. Material UI provides built-in support for handling errors and displaying validation messages. For instance, you can use the required prop on the component you wish to mark as required.

Doing this will implement browser-level validation as seen in the image below.

Browser level form validation error

Let’s take it a step further and implement a custom validation.

Creating a Registration Form With Input Validation

For this example, create a FormValidationExample component that includes form validation and error states for a simple registration form with a name and email field. We’ll use React’s useState and Material UI’s TextField component.

Start by importing React, useState, and Material UI TextField and Button components.

import React, { useState } from 'react';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';

Next, create the FormValidationExample component. For this, copy and paste the code snippet below.

import React, { useState } from 'react';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';

function FormValidationExample() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
  });

  const [errors, setErrors] = useState({
    name: '',
    email: '',
  });

  const validateForm = () => {
    const newErrors = {
      name: formData.name === '' ? 'Name is required' : '',
      email: formData.email === '' ? 'Email is required' : '',
    };
    setErrors(newErrors);

    return !Object.values(newErrors).some(Boolean);
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
    setErrors({ ...errors, [name]: '' });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (validateForm()) {
      // Submit the form or perform further actions here
      console.log('Form data:', formData);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <TextField
        name="name"
        label="Name"
        variant="outlined"
        color="secondary"
        sx={{my:1}}
        fullWidth
        value={formData.name}
        onChange={handleInputChange}
        error={Boolean(errors.name)}
        helperText={errors.name}
      />
      <TextField
        name="email"
        label="Email"
        variant="outlined"
        fullWidth
        color="secondary"
        sx={{my:1}}
        value={formData.email}
        onChange={handleInputChange}
        error={Boolean(errors.email)}
        helperText={errors.email}
      />
      <Button 
        type="submit"
        color="secondary"
        sx={{my:1}}
        variant="contained"
        fullWidth
       >Register</ Button>
    </form>
  );
}

export default FormValidationExample;

In the code above, we are creating a FormValidationExample functional component and setting up the initial state using useState for formData (to store form data) and errors (to store validation error messages).

The validateForm function checks whether the form is valid and updates the error state accordingly. It returns true if the form is valid and false if there are errors.

The handleInputChange function is the event handler for input changes. It updates formData and clears the corresponding error when the user interacts with the input fields.

handleSubmit function is called when the form is submitted. It calls validateForm to check if the form is valid before taking further action.

The TextField components include an error prop, which is set to true if there’s an error, and a helperText prop, which displays the validation error message.

With this code, you have a simple registration form with form validation and error handling using Material UI’s TextField components. The error messages are displayed under the input fields when there are validation issues. This implementation will override the default browser validation that MUI provides with the required prop.

Form with validation error

If the user fills one of the fields, the form won’t submit as well.

Partially filled form

The form will only validate if both fields aren’t empty. Once you click the Register button, the value is logged in the console.

Validated form

Frequently Asked Questions

Below, we’ve answered some top questions about using Material UI input elements.

How do I customize my MUI input?

Material UI provides various ways to customize input components, including styling, modifying labels and borders, and handling form validation.

What are the different types of text fields in material UI?

Material UI supports different text input components, including TextField, OutlinedInput, and FilledInput. These components cater to various design and usage preferences.

Can you use input in React?

Yes, you can use input fields in React applications. Material UI Input components are designed to work seamlessly with React and TypeScript-based projects.

How do I install Material UI Input components into my React project?

To install MUI Input components, you’ll first need to make sure material UI is installed on your project. Once you install the library, you’ll be able to use the components it supports on your project including text and input components.

Can I use Material UI Inputs with plain HTML and CSS, or are they exclusive to React?

Material UI Input components are primarily designed for React applications. While you can use them with plain HTML and CSS, it’s recommended to take full advantage of their features in a React environment.

How can I create custom input styles using Material UI?

You can create custom input styles using Material UI by adjusting the CSS-in-JS (JSS) within your component or by applying classes and overriding default Material UI styles.

Are Material UI Input components compatible with form validation libraries?

Yes, Material UI Input components can be used with popular form validation libraries like Formik and Yup. You can easily integrate them to handle validation and error states.

Other Resources

For more tips on how to use other Material UI components, check out the following tutorials.

Also check out the video below to learn more about Material UI.

Final Thoughts

Inputs are an essential part of any web project. These fields allow you to interact with your users and receive feedback from them as well. For example, adding a comment form on your blog to receive feedback about the content you post.

There are other use cases of input components like creating registration and login forms, eCommerce checkout forms, blog post forms, etc.

In this guide, we’ve explained the various input fields Material UI supports and how to import and use them. This should give you a head start and make you feel a bit comfortable when using these components for your projects.

If you enjoyed reading this tutorial, we recommend checking out our ready-made templates. PureCode uses AI to generate templates that serve as building blocks for web applications. This in turn cuts down development time.

Explore Material UI Templates

David Ozokoye

David Ozokoye

Software Engineer and Technical Writer