Skip to content

Instantly share code, notes, and snippets.

@chriskavanagh
Created March 30, 2019 08:37
Show Gist options
  • Save chriskavanagh/339744f8709294ca45ab620eaf41f82c to your computer and use it in GitHub Desktop.
Save chriskavanagh/339744f8709294ca45ab620eaf41f82c to your computer and use it in GitHub Desktop.
import React, { Component } from "react";
import Input from "./common/Input";
export default class LoginForm extends Component {
state = {
username: "",
password: "",
errors: {}
};
validate = () => {
const errors = {};
if (this.state.username.trim() === "") {
errors.username = "Username is required";
}
if (this.state.password.trim() === "") {
errors.password = "Password is required";
}
return Object.keys(errors).length === 0 ? null : errors;
};
handleSubmit = e => {
e.preventDefault();
const errors = this.validate();
console.log(errors);
this.setState({ errors: errors || {} });
if (errors) return;
};
validateProperty = (input, e) => {
const { value } = e.target;
if (input === "username") {
if (value.trim() === "") return "Username is required";
}
if (input === "password") {
if (value.trim() === "") return "Password is required";
}
};
handleChange = input => e => {
console.log(e.target.value, input);
const errors = { ...this.state.errors };
const errorMessage = this.validateProperty(input, e);
if (errorMessage) errors[input] = errorMessage;
else delete errors[input];
this.setState({
[input]: e.target.value,
errors: errors
});
};
/* handleChange = e => {
const { name, value } = e.target;
this.setState({
[name]: value
});
}; */
render() {
const { username, password, errors } = this.state;
return (
<div>
<h1>Login</h1>
<form onSubmit={this.handleSubmit}>
<Input
name="username"
value={username}
label="Username"
onChange={this.handleChange}
type={"text"}
error={errors.username}
/>
<Input
name="password"
value={password}
label="Password"
onChange={this.handleChange}
type={"password"}
error={errors.password}
/>
<button className="btn btn-primary">Login</button>
</form>
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment