Created
September 24, 2023 16:16
-
-
Save osamajavaid/63aaed12ef972477730e5d1536b22d7d to your computer and use it in GitHub Desktop.
React useForm hook: Creates a stateful value from the fields in a form.
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
const useForm = initialValues => { | |
const [values, setValues] = React.useState(initialValues); | |
return [ | |
values, | |
e => { | |
setValues({ | |
...values, | |
[e.target.name]: e.target.value | |
}); | |
} | |
]; | |
}; | |
/////////////////// | |
// Example | |
/////////////////// | |
const Form = () => { | |
const initialState = { email: '', password: '' }; | |
const [values, setValues] = useForm(initialState); | |
const handleSubmit = e => { | |
e.preventDefault(); | |
console.log(values); | |
}; | |
return ( | |
<form onSubmit={handleSubmit}> | |
<input type="email" name="email" onChange={setValues} /> | |
<input type="password" name="password" onChange={setValues} /> | |
<button type="submit">Submit</button> | |
</form> | |
); | |
}; | |
ReactDOM.createRoot(document.getElementById('root')).render( | |
<Form /> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment