Created
May 31, 2019 15:39
-
-
Save cdaz5/2801202ebcc0e19eb391995de962d887 to your computer and use it in GitHub Desktop.
Form w/ Hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react'; | |
import logo from './logo.svg'; | |
import './App.css'; | |
function App() { | |
const notNull = (v) => v ? undefined : 'can\'t be null'; | |
const isChris = (v) => v ? undefined : 'can\'t be chris'; | |
const formInputs = [ | |
{ | |
name: 'firstName', | |
type: 'text', | |
validations: [ | |
notNull, | |
isChris | |
] | |
}, | |
{ | |
name: 'lastName', | |
type: 'text' | |
}, | |
{ | |
name: 'email', | |
type: 'email' | |
}, | |
{ | |
name: 'password', | |
type: 'password' | |
}, | |
] | |
const [input, setInput] = useState(formInputs.reduce((obj, curr) => ({ | |
...obj, | |
[curr.name]: { val: '', err: [] } | |
}), {})); | |
const onChange = (e) => setInput({ | |
...input, | |
[e.target.name]: { | |
...input[e.target.name], | |
val: e.target.value | |
} | |
}) | |
const validate = (state) => { | |
const errs = formInputs.flatMap(inp => | |
inp.validations && | |
inp.validations.map(validator => { | |
const error = validator(state[inp.name].val) | |
return error && { | |
name: inp.name, | |
msg: error | |
} | |
}) | |
) | |
const newState = errs.reduce((acc, val) => (val ? { | |
...acc, | |
[val.name]: { | |
...acc[val.name], | |
err: [...acc[val.name].err, val.msg] | |
} | |
} : acc), state) | |
setInput(newState) | |
} | |
console.log(input) | |
return ( | |
<div className="App" style={{ display: "flex", flexDirection: "column" }}> | |
<form onSubmit={(e) => { | |
e.preventDefault(); | |
validate(input) | |
}}> | |
{formInputs.map(({ name, type }) => ( | |
<div key={name}> | |
<input | |
value={input[name].val} | |
onChange={onChange} | |
key={name} | |
name={name} | |
type={type} | |
/> | |
<div>{input[name].err.map(msg => <div key={msg}>{msg}</div>)}</div> | |
</div> | |
))} | |
{/* <div> | |
<label>First Name</label> | |
<input value={input['firstName'].val} onChange={onChange} type="text" name="firstName" required /> | |
</div> | |
<div> | |
<label>Last Name</label> | |
<input value={input['lastName'].val} onChange={onChange} type="text" name="lastName" required /> | |
</div> | |
<div> | |
<label>Email Address</label> | |
<input value={input['email'].val} onChange={onChange} type="email" name="email" required /> | |
</div> | |
<div> | |
<label>Password</label> | |
<input value={input['password1'].val} onChange={onChange} type="password" name="password1" /> | |
</div> */} | |
<button type="submit">Sign Up</button> | |
</form> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment