Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Material UI Form with React Hook Form with Validation using Yup
import React from "react";
import { makeStyles, createStyles, Theme } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import Box from '@material-ui/core/Box';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';
import { Button } from '@material-ui/core';
import { useForm } from 'react-hook-form';
import * as yup from 'yup';
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
flexGrow: 1,
},
paper: {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
},
container: {
display: 'flex',
flexWrap: 'wrap',
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
},
dense: {
marginTop: theme.spacing(2),
},
menu: {
width: 200,
},
button: {
margin: theme.spacing(1),
},
extendedIcon: {
marginRight: theme.spacing(1),
},
}),
);
export default function Login() {
const classes = useStyles();
let loginSchema = yup.object().shape({
email: yup.string().email().required(),
password: yup.string().required()
});
const { register, handleSubmit, errors} = useForm({
validationSchema: loginSchema
});
const onSubmit = (values: any) => {
console.log(values);
// ${process.env.REACT_APP_API_BASE}/api/v1/users/login/
fetch('http://localhost:8000/api/v1/users/login/', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
// mode: 'cors',
body: JSON.stringify({ 'email': values.email, 'password': values.password })
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err);
})
}
return (
<div className={classes.root}>
<Box mt={5} px={2}>
<Grid container spacing={3}
direction="row"
justify="center"
alignItems="center"
>
<Grid item xs={12} sm={8} md={6} lg={4}>
<Paper className={classes.paper}>
<Typography variant="h3" gutterBottom>
Login
</Typography>
<form onSubmit={handleSubmit(onSubmit)} className={classes.container}>
<TextField
name="email"
inputRef={register}
label="Enter email"
className={classes.textField}
margin="normal"
variant="outlined"
fullWidth
error={errors.email ? true : false}
/>
<TextField
name="password"
type="password"
inputRef={register}
label="Enter password"
className={classes.textField}
margin="normal"
variant="outlined"
fullWidth
error={errors.email ? true : false}
/>
<Button className={classes.button} type="submit" variant="outlined" aria-label="delete" color="primary" >
Continue
</Button>
</form>
</Paper>
</Grid>
</Grid>
</Box>
</div>
)
}
@SeyyedHesam

This comment has been minimized.

Copy link

@SeyyedHesam SeyyedHesam commented May 18, 2020

import { useForm } from 'react-hook-form'; not import useForm from 'react-hook-form';

@cmcWebCode40

This comment has been minimized.

Copy link

@cmcWebCode40 cmcWebCode40 commented Aug 22, 2020

While using an external form validator library like yup you have to install the @hookform/resolvers in order to seemlessly use yup
see react-hook-form docs for more info react-hook-form

       import { yupResolver } from '@hookform/resolvers';
........
      export default function Login() {
........
	const { handleSubmit, register, errors } = useForm({
		resolver: yupResolver(SignUpSchema)
	});
}
@gondo

This comment has been minimized.

Copy link

@gondo gondo commented Aug 23, 2020

console.log(err); is useless for users, this also requires visual feedback to user

@saba-bg

This comment has been minimized.

Copy link

@saba-bg saba-bg commented Nov 11, 2020

i try to write a simple validation with hooks...
https://github.com/saba-bg/react-material-ui-form-validator-with-hooks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment