myTest532 myTest532
myTest532 myTest532

Reputation: 2381

React Hook Form and Input type file

I'm trying to use an input type file with a React Hook Form.

import { Controller, useForm } from "react-hook-form";
import {
    Button,
    Form, FormText,
    Label,
    Input,
} from 'reactstrap';

const Test = () => {
  
  const { handleSubmit, control, setValue, formState: { errors }} = useForm();

  // I have other inputs and divs. Just showing the file here
  return (
     <Controller
        name="file"
        control={control}
        render={({ field }) => (
           <Input {...field} type="file" id="file" />
        )}
     />
  );
}

When I submit the form and check the data.file it has only: C:\fakepath\myFile.pdf

const submitForm = (data) => {
   console.log(data.file);
}

Upvotes: 2

Views: 11329

Answers (1)

Andr&#233;s Sapatanga
Andr&#233;s Sapatanga

Reputation: 186

I hope it's not too late.

I added a custom onChange of react-hook-form to pass value and name.

   <Controller
      name="profilePath"
      control={control}
      render={({ field }) => (
        <ImgUpload
          src={
            !field.value
              ? userSvg
              : field.value instanceof File
              ? URL.createObjectURL(field.value)
              : field.value
          }
          onChange={(e) =>
            field.onChange({ target: { value: e.target.files[0], name: field.name } })
          }
        />
      )}
    />

Upvotes: 4

Related Questions