-
Notifications
You must be signed in to change notification settings - Fork 0
/
LogInForm.tsx
108 lines (105 loc) · 3 KB
/
LogInForm.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import { Form, Button, Alert } from "react-bootstrap";
import { Formik } from "formik";
import { useState } from "react";
export interface LogInFormValues {
username: string;
password: string;
}
const initialValues: LogInFormValues = {
username: "",
password: "",
};
const LogInForm: React.FC<{
handleSubmit: (input: LogInFormValues) => Promise<void>;
}> = ({ handleSubmit }) => {
const [error, setError] = useState("");
return (
<Formik
initialValues={initialValues}
validate={(values) => {
const errors: { username?: string; password?: string } = {};
if (!values.username) {
errors.username = "Username required";
}
if (!values.password) {
errors.password = "Password required";
}
return errors;
}}
onSubmit={async (values) => {
try {
await handleSubmit(values);
} catch (error) {
setError(error.message);
}
}}
>
{({
values,
errors,
touched,
setValues,
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
}) => (
<>
{error && <Alert variant="danger">{error}</Alert>}
<Form onSubmit={handleSubmit} noValidate>
<Form.Text muted className="mb-2">
You can use a test account!{" "}
<Button
size="sm"
variant="outline-secondary"
onClick={() => {
setValues({ username: "test", password: "123" });
}}
>
Fill form
</Button>
</Form.Text>
<Form.Group>
<Form.Label>Username</Form.Label>
<Form.Control
type="text"
name="username"
placeholder="Username"
value={values.username}
onChange={handleChange}
onBlur={handleBlur}
isInvalid={!!(touched.username && errors.username)}
/>
<Form.Control.Feedback type="invalid">
{errors.username}
</Form.Control.Feedback>
</Form.Group>
<Form.Group>
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
name="password"
placeholder="Password"
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
isInvalid={!!(touched.password && errors.password)}
/>
<Form.Control.Feedback type="invalid">
{errors.password}
</Form.Control.Feedback>
</Form.Group>
<Button
className="d-block mx-auto w-50"
type="submit"
disabled={isSubmitting}
>
Sign In
</Button>
</Form>
</>
)}
</Formik>
);
};
export default LogInForm;