I want to use a MUI file upload Button in React-Hook-Form. When a file passing all validations is selected, the file name needs to be shown next to the Button. Also, following 3 validations are required.
-
A file must be uploaded.
-
File type must be application/pdf, image/gif, image/jpeg, image/png or image/tiff.
-
File size must be less than 10MB.
import {Controller, useForm} from "react-hook-form";
export const Demo = () => {
const {control} = useForm({
defaultValues: {
file: null,
}
});
return (
<form>
<FormControl>
<Controller
name="file"
control={control}
rules={{required: "File is required."}}
render={({field, fieldState: {error}}) => (
<Button
{...field}
component="label"
variant="contained"
>
File Upload
<input
hidden
type="file"
accept=".pdf,image/gif,image/jpeg,image/png,image/tiff"
/>
</Button>
)}
/>
</FormControl>
{file && <FormLabel>{file.name}</FormLabel>}
</form>
)
}
If I use const [file, setFile] = useState(null)
to maintain the state of file, then {file && <FormLabel>{file.name}</FormLabel>}
will work. However, since react-hook-form is used, we don’t need to use useState()
to track the state. How can the file name be shown when it’s uploaded?
Also, since there are no error
and helperText
props for MUI Button
, error={!!error}
and helperText={error?.message}
can’t be used. How can the error message “File is required.” be shown? If I don’t use yup as the validation library, can validations of file name and file size still be implemented and the corresponding error message still be shown in react-hook-form?