Skip to content

Instantly share code, notes, and snippets.

@whisher
Last active January 28, 2023 06:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save whisher/c8e0453a5fa76b5d6d952919c77ef0c4 to your computer and use it in GitHub Desktop.
Save whisher/c8e0453a5fa76b5d6d952919c77ef0c4 to your computer and use it in GitHub Desktop.
reactjs typescript useForm - a simple custom hook to manage form in react
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