get selected file object with react-hook-form

Viewed 905

I have a component which uploads a file. When an image is selected it previews it in another component.

So, when an image is selected, I need to access it. I tried using getValues() and watch() from react-hook-form but it is returning me path of the file in string form not the file object.

          <div className="photo">
            <Avatar
              src={
                // it gives path of the file as string
                getValues('photo')
                  ? URL.createObjectURL(getValues('photo')[0])
                  : "https://icon-library.com/images/no-image-icon/no-image-icon-0.jpg"
              }
              alt="photo preview"
              sx={{ width: "200px", height: "200px" }}
            />
            <label htmlFor="contained-button-file">
              <Controller
                name="photo"
                control={control}
                render={({ field }) => (
                  <Input
                    {...field}
                    accept="image/*"
                    id="contained-button-file"
                    type="file"
                    error={Boolean(errors["photo"])}
                    helperText={errors["photo"]?.message}
                  />
                )}
              />
              <Button variant="contained" component="span">
                Upload
              </Button>
            </label>
          </div>

Somehow, watch() and getValues() reading value of input field here. While they should be returning e.target.files instead.

It can be checked here and here, It works the same way. It returns the files.

Why it does not return files but returning value here?

1 Answers

Using work around for now. Using setValue() and calling it on change of the input file.

          <div className="photo">
            <Avatar
              src={
                watch('photo')
                  ? URL.createObjectURL(watch('photo')[0])
                  : "https://icon-library.com/images/no-image-icon/no-image-icon-0.jpg"
              }
              alt="photo preview"
              sx={{ width: "200px", height: "200px" }}
            />
            <label htmlFor="contained-button-file">
              <Input
                accept="image/*"
                id="contained-button-file"
                type="file"
                error={Boolean(errors["photo"])}
                onChange={(e) => setValue("photo", e.target.files)}
                multiple
                helperText={errors["photo"]?.message}
              />

              <Button variant="contained" component="span">
                Upload
              </Button>
            </label>
          </div>
Related