Material-UI (MUI) can be a powerful tool in building a responsive user interfaces in React. One useful application of MUI is creating controlled forms. In a controlled form, form elements (such as inputs) are tied to the component state, allowing you to manage and validate user inputs in real-time.
Walkthrough of creating a controlled form using MUI.
Set Up Your Project
Create a new React project and install MUI:
npx create-react-app my-app
cd my-app
npm install @mui/material
Import Necessary Components
For this example, we’ll be using MUI’s TextField, Button, and Box components.
import React, { useState } from "react";
import { TextField, Button, Box } from "@mui/material";
Create the Form State
In a controlled form, the input values are stored in the component’s state. We need to create a useState hook to manage these values.
const [formData, setFormData] = useState({
name: "",
email: ""
});
Handle Input Changes
To control the form inputs, each TextField component’s value will be set to the corresponding state value, and onChange will update the state.
const handleChange = (e) => {
const { name, value } = e.target;
setFormData((prevState) => ({
...prevState,
[name]: value,
}));
};
Build the Form
Now, we can put everything together inside a form. Each input field will be controlled by the component’s state. Don't forget to use export default
in order to use your component in your other project files!
export default function ControlledForm() {
const [formData, setFormData] = useState({
name: "",
email: ""
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData((prevState) => ({
...prevState,
[name]: value,
}));
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData);
// Add form submission logic here
};
return (
<Box
component="form"
onSubmit={handleSubmit}
sx={{ display: "flex", flexDirection: "column", gap: 2 }}
>
<TextField
label="Name"
name="name"
value={formData.name}
onChange={handleChange}
fullWidth
/>
<TextField
label="Email"
name="email"
value={formData.email}
onChange={handleChange}
fullWidth
/>
<Button type="submit" variant="contained">
Submit
</Button>
</Box>
);
}
Explanation
TextField: Renders a material-styled text input. The value is controlled by formData.name and formData.email, and onChange updates the state when the user types in the input field.
Button: Triggers form submission, which is handled using handleSubmit.
Box: A wrapper from MUI that handles layout and styling.
Final Thoughts
Creating controlled forms in MUI allows you to handle user input efficiently. Using MUI helps customize validation, formatting, and submission handling. MUI’s components not only makes the form look more appealing, but also simplifies the development process with their user-friendly APIs.
Top comments (0)