I am trying to build a simple form in MUI with login and password TextField
and a Button
to submit the form. What's the best way to handle events on the Button
and submit the form?
MUI does not have a form component. Instead, MUI relies on the React form component. However, it has many components intended for use inside a form. Examples include FormControl, TextField, FormLabel, and many more.
Create a Form Let's start by creating a new file in our project called Form. js . This component will return a form and we will be using the TextField and Button components from Material-UI. We will pass down the handleClose prop from the ModalDialog component to use in a cancel button.
The form submit() Method in HTML DOM is used to send the form data to the web-server. It works as same as submit button. It does not contain any parameters.
Add type="submit"
to a Material UI button element, such as a RaisedButton, and it will work as a submit button when clicked on. When the form is submitted, it will trigger the onSubmit on the form and run the handleSubmit callback.
class MyForm extends React.Component {
constructor() {
super();
this.state = {id: null};
}
handleChange = (event) => {
this.setState({id: event.target.value});
}
handleSubmit = (event) => {
//Make a network call somewhere
event.preventDefault();
}
render() {
return(
<form onSubmit={this.handleSubmit}>
<TextField floatingLabelText="ID Number" onChange={this.handleChange} />
<RaisedButton label="Submit" type="submit" />
</form>
)
}
}
You can have a look at react-hook-form library. It manages the form state for you automatically, the only thing you need to do is specify the name for each field and validation rule if needed:
const { register, handleSubmit } = useForm();
const onSubmit = (data) => alert(JSON.stringify(data, null, 4));
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Stack m={2} spacing={3}>
<TextField label="First Name" inputProps={register('firstName')} />
<TextField label="Last Name" inputProps={register('lastName')} />
<TextField select label="Gender" inputProps={register('gender')}>
<MenuItem value="male">Male</MenuItem>
<MenuItem value="female">Female</MenuItem>
<MenuItem value="furry">Furry</MenuItem>
</TextField>
<FormControlLabel
control={<Checkbox />}
label="Is developer?"
{...register('isDeveloper')}
/>
<Button variant="contained" type="submit">
submit
</Button>
</Stack>
</form>
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With