Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hook form: How to can I use onChange on React Hook Form Version 7.0

Previously I used to write like this:

<input className="form-control" name="productImage" type='file' onChange={handleImageUpload} ref={register({ required: true })} />

After the update I have to write like this:

<input className="form-control" type="file" {...register('productImage', { required: true })} />

How do I use onChange={handleImageUpload} on the updated version of React Hook Form? Here is the migration docs

Please pardon my mistakes in the manner of asking the question. I'm new to these things. Thank you.

like image 394
Mehnaz Khan Avatar asked Apr 03 '21 21:04

Mehnaz Khan


People also ask

How do you use Defaultvalues in React hook form?

The solution is to use the reset() function from the React Hook Form library, if you execute the function without any parameters ( reset() ) the form is reset to its default values, if you pass an object to the function it will set the form with the values from the object (e.g. reset({ firstName: 'Bob' }) ).

How do you use a date picker with React hook form?

To use react-datepicker with React hooks forms, we can wrap it in the Controller component. We call the useForm hook to return an object with various properties we use to add the date picker into the form. Next, we add the Controller component in the form.


1 Answers

You just have to move the onChange props after {...register(...)}

const productImageField = register("productImage", { required: true });

return (
    <input
        className="form-control"
        type="file"
        {...productImageField}
        onChange={(e) => {
          productImageField.onChange(e);
          handleImageUpload(e);
     }}
    />
)

(Dec 3 2021) edit: this approach is no longer correct since react-hook-form v7.16.0's changes, see @Bill's answer.

like image 85
Joris Avatar answered Sep 24 '22 15:09

Joris