Uploading a file using only the input field - React Hook Form

Viewed 9460

I'm my app, I have a file input to submit a file and send it to a firebase storage bucket. I'm using the react-hook-form library for this task. The problem is, that I wanted to make the file to be uploaded by only having the input element, I didn't want to have a button to submit it. This is all related to the styles, I could make a submit button and it would certainly work. I saw a video in which the author shows how to create this functionality and even integrate it with firebase, but he has a submit button

This is my how he did it

import React from "react";
import { useForm } from "react-hook-form";

function App() {
  const { register, handleSubmit } = useForm() 

  const onSubmit = (data) => {
    console.log(data)
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input ref={register} type="file" name="picture" />
      <button>Submit</button>
    </form>
  );
}

export default App;

To see the firebase implementation, you can check this link

2 Answers

You basically have to upload the file in the input's onChange handler instead of the form's onSubmit. The code should look something like this:

function App() {
  const onChange = (e) => {
    const storageRef = app.storage().ref();
    const fileRef = storageRef.child(e.target.files[0].name);
    fileRef
      .put(e.target.files[0])
      .then(() => {
        console.log('Uploaded a file');
      });
  }

  return (
    <form>
      <input type="file" onChange={onChange} />
    </form>
  );
}

ReactDOM.render(<App />, document.querySelector("#app"))

Those who are new to REACT HOOK FORM and need to render OnChange of a particular field, then use watch from the useForm methods.

const methods = useForm();
methods.watch(); // to render on all fields change
methods.watch(['fieldName1', 'fieldName2' ]); // to render on a particular field onChange
Related