Forked from whisher/gist:c8e0453a5fa76b5d6d952919c77ef0c4
Created
May 18, 2020 06:48
-
-
Save tonycaputome/abe8e0dcf1df27c61b6d89ae5c2c410c to your computer and use it in GitHub Desktop.
reactjs typescript useForm - a simple custom hook to manage form in react
This file contains 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
Credit to | |
https://medium.com/javascript-in-plain-english/react-controlled-forms-with-hooks-538762aab935 | |
import React, { ChangeEvent, FormEvent, useReducer } from "react"; | |
const useForm = (initialState: any) => { | |
const reducer = ( | |
state: typeof initialState, | |
payload: { field: string; value: string } | |
) => { | |
return { | |
...state, | |
[payload.field]: payload.value, | |
}; | |
}; | |
const [state, dispatch] = useReducer(reducer, initialState); | |
const handleChange = (e: ChangeEvent<HTMLInputElement>) => { | |
dispatch({ field: e.target.name, value: e.target.value }); | |
}; | |
return { | |
state, | |
bind: { | |
onChange: handleChange, | |
}, | |
}; | |
}; | |
const Auth: React.FC = () => { | |
const initialState = { | |
email: "", | |
password: "", | |
}; | |
const submitHandler = (e: FormEvent<HTMLFormElement>) => { | |
e.preventDefault(); | |
console.log(state); | |
}; | |
const { state, bind } = useForm(initialState); | |
const { email, password } = state; | |
return ( | |
<div> | |
<form onSubmit={submitHandler}> | |
<div> | |
<input type="text" name="email" {...bind} value={email} /> | |
</div> | |
<div> | |
<input type="password" name="password" {...bind} value={password} /> | |
</div> | |
<button type="submit">Send</button> | |
</form> | |
</div> | |
); | |
}; | |
export default Auth; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment