Files
30-seconds-of-code/snippets/useForm.md
Gisela Miranda Difini 5221e2e147 Add useForm hook (#111)
Co-authored-by: Gisela <gisela.difini@4all.com>
Co-authored-by: Angelos Chalaris <chalarangelo@gmail.com>
2021-09-02 19:12:46 +03:00

1.1 KiB

title, tags, firstSeen
title tags firstSeen
useForm hooks,state,beginner 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.
const useForm = initialValues => {
  const [values, setValues] = React.useState(initialValues);

  return [
    values,
    e => {
      setValues({
        ...values,
        [e.target.name]: e.target.value
      });
    }
  ];
};
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.render(<Form />, document.getElementById('root'));