What is the best practice for handling a form?

Viewed 36

Im new to react and the way I handle a form to make a request is the following: let's imagine that I have a form that have 3 inputs: Name, Lastname, Phone

I use a react hook state to save the data

const [form, setForm] = useState({
    name: "",
    lastname: "",
    phone: "",
});

Then to handle the data from the input I use the next function:

const handle = (e) => {
    const getData = {...form};
    getData[e.target.id] = e.target.value;
    setForm(getData);
}

and the input have something like this:

<input type="text" id="name" required onChange={(e) => handle(e)} />

Should I keep using this or what do you recommend me?

1 Answers

There is nothing wrong how you handle the form. But when it comes to bigger applications formik is a one of popular library use. Also you can have custom hook to handle forms if you want. For a example,

const useForm = (initialValues) => {
    const [values, setValues] = useState(initialValues);
  
  const onChangeHandler = (e) => {
    const { name, value } = e.target;
    setValues({ ...values, [name]: value });
  }
  
  return [values, onChangeHandler];
}

In your component

const [values, onChangeHandler] = useForm({ name: "", lastname: "", phone: "", })
Related