Open In App

How to Handle Forms in Material UI ?

In Material UI, managing forms is made easy with a variety of intuitive components and features. It streamlines user input and validation processes in React applications by utilizing form components such as TextField, Select, and Checkbox.

Installation

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

The table below illustrates the terms alongside their descriptions.

Term Description
@mui/material Package containing Material UI components.
@emotion/react Required for styling components with Emotion.
@emotion/styled Required for styling components with Emotion.

Features

Approach

Example:

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

function MyForm() {
const [formData, setFormData] = useState({
username: '',
password: '',
});

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

const handleSubmit = (event) => {
event.preventDefault();
// Handle form submission logic
};

return (
<form onSubmit={handleSubmit}>
<TextField
label="Username"
name="username"
value={formData.username}
onChange={handleChange}
fullWidth
margin="normal"
/>
<TextField
label="Password"
name="password"
type="password"
value={formData.password}
onChange={handleChange}
fullWidth
margin="normal"
/>
<Button type="submit" variant="contained" color="primary">
Submit
</Button>
</form>
);
}

export default MyForm;
Article Tags :