From 5221e2e147c423a36945d7608c85a6ac222fc7bd Mon Sep 17 00:00:00 2001 From: Gisela Miranda Difini Date: Thu, 2 Sep 2021 13:12:46 -0300 Subject: [PATCH] Add `useForm` hook (#111) Co-authored-by: Gisela Co-authored-by: Angelos Chalaris --- snippets/useForm.md | 48 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 snippets/useForm.md diff --git a/snippets/useForm.md b/snippets/useForm.md new file mode 100644 index 000000000..ce8452329 --- /dev/null +++ b/snippets/useForm.md @@ -0,0 +1,48 @@ +--- +title: useForm +tags: hooks,state,beginner +firstSeen: 2021-09-17T05:00:00-04:00 +--- + +Creates a stateful value from the fields in a form. + +- Use the `useState()` hook to create a state variable for the values in the form. +- Create a function that will be called with an appropriate event by a form field and update the state variable accordingly. + +```jsx +const useForm = initialValues => { + const [values, setValues] = React.useState(initialValues); + + return [ + values, + e => { + setValues({ + ...values, + [e.target.name]: e.target.value + }); + } + ]; +}; +``` + +```jsx +const Form = () => { + const initialState = { email: '', password: '' }; + const [values, setValues] = useForm(initialState); + + const handleSubmit = e => { + e.preventDefault(); + console.log(values); + }; + + return ( +
+ + + +
+ ); +}; + +ReactDOM.render(
, document.getElementById('root')); +```