Created
May 21, 2024 09:43
-
-
Save amitasaurus/5a302b8a5d0ea84a4fbbe608742cb991 to your computer and use it in GitHub Desktop.
react hook to manage form
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 { useFormFields } from '../lib/hooks/useFormFields'; | |
type Props = {}; | |
export default function Form({}: Props) { | |
const [fields, handleFieldChange] = useFormFields({ | |
email: '', | |
password: '', | |
}); | |
function handleFormSubmit() { | |
console.log(fields); | |
} | |
return ( | |
<form> | |
<div> | |
<label htmlFor="email">Enter Email</label> | |
<input | |
type="email" | |
name="email" | |
id="email" | |
value={fields.email} | |
onChange={handleFieldChange} | |
/> | |
</div> | |
<div> | |
<label htmlFor="password">Enter Password</label> | |
<input | |
type="password" | |
name="password" | |
id="password" | |
value={fields.password} | |
onChange={handleFieldChange} | |
/> | |
</div> | |
<button type="button" onClick={handleFormSubmit}> | |
Submit | |
</button> | |
</form> | |
); | |
} |
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 { useState, ChangeEvent, ChangeEventHandler } from 'react'; | |
interface FieldsType { | |
[key: string | symbol]: string; | |
} | |
export function useFormFields( | |
initialState: FieldsType | |
): [FieldsType, ChangeEventHandler] { | |
const [fields, setValues] = useState(initialState); | |
return [ | |
fields, | |
function (event: ChangeEvent<HTMLInputElement>) { | |
setValues({ | |
...fields, | |
[event.target.id]: event.target.value, | |
}); | |
return; | |
}, | |
]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment