-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
88 lines (76 loc) · 2.1 KB
/
App.js
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
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./index.css";
function App() {
// React States
const [errorMessages, setErrorMessages] = useState({});
const [isSubmitted, setIsSubmitted] = useState(false);
// User Login info
const database = [
{
username: "user1",
password: "pass1"
},
{
username: "user2",
password: "pass2"
}
];
const errors = {
uname: "invalid username",
pass: "invalid password"
};
const handleSubmit = (event) => {
//Prevent page reload
event.preventDefault();
var { uname, pass } = document.forms[0];
// Find user login info
const userData = database.find((user) => user.username === uname.value);
// Compare user info
if (userData) {
if (userData.password !== pass.value) {
// Invalid password
setErrorMessages({ name: "pass", message: errors.pass });
} else {
setIsSubmitted(true);
}
} else {
// Username not found
setErrorMessages({ name: "uname", message: errors.uname });
}
};
// Generate JSX code for error message
const renderErrorMessage = (name) =>
name === errorMessages.name && (
<div className="error">{errorMessages.message}</div>
);
// JSX code for login form
const renderForm = (
<div className="form">
<form onSubmit={handleSubmit}>
<div className="input-container">
<label>Username </label>
<input type="text" name="uname" required />
{renderErrorMessage("uname")}
</div>
<div className="input-container">
<label>Password </label>
<input type="password" name="pass" required />
{renderErrorMessage("pass")}
</div>
<div className="button-container">
<input type="submit" />
</div>
</form>
</div>
);
return (
<div className="app">
<div className="login-form">
<div className="title">Sign In</div>
{isSubmitted ? <div>User is successfully logged in</div> : renderForm}
</div>
</div>
);
}
export default App;