material ui hook useform code example
Example: react hook form rating material ui
import React, { useState } from "react";
import Checkbox from "@material-ui/core/Checkbox";
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Typography from "@material-ui/core/Typography";
import { makeStyles } from "@material-ui/core/styles";
import Container from "@material-ui/core/Container";
import { useForm } from "react-hook-form";
import Rating from "@material-ui/lab/Rating";
import StarBorderIcon from '@material-ui/icons/StarBorder';
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(8),
display: "flex",
flexDirection: "column",
alignItems: "center"
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: theme.spacing(1)
},
submit: {
margin: theme.spacing(3, 0, 2)
}
}));
export default function Create() {
const classes = useStyles();
const [rating, setRating] = useState(2);
const { register, handleSubmit } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<Container component="main" maxWidth="xs">
<div className={classes.paper}>
<Typography component="h1" variant="h5">
Form
</Typography>
<form
className={classes.form}
noValidate
onSubmit={handleSubmit(onSubmit)}
>
<TextField
variant="outlined"
margin="normal"
fullWidth
id="title"
label="Title"
name="title"
autoFocus
inputRef={register()}
/>
<FormControlLabel
control={
<Checkbox
inputRef={register}
name="remember"
defaultValue={false}
/>
}
label="remember"
/>
<br />
<FormControlLabel
control={
<>
<input
name="rating"
type="number"
value={rating}
ref={register}
hidden
readOnly
/>
<Rating
name="rating"
value={rating}
precision={0.5}
onChange={(_, value) => {
setRating(value);
}}
icon={<StarBorderIcon fontSize="inherit" />}
/>
</>
}
label="select rating"
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Submit
</Button>
</form>
</div>
</Container>
);
}