RHFFileUploader
RHFFileUploader component is a flexible and easy-to-use file input field built supporting both single and multi-file uploads, optional file type and size validation, and customizable UI elements such as the upload button and file list items.
Usage
import RHFFileUploader, { RHFFileUploaderProps, FileUploadError } from '@nish1896/rhf-mui-components/mui/file-uploader';
Here’s a basic example of the component configured to accept a single file:
<RHFFileUploader
fieldName="resume"
control={control}
errorMessage={errors?.resume?.message}
/>
A file object has the following properties:
{
lastModified: 1738870405923,
lastModifiedDate: "Fri Feb 07 2025 01:03:25 GMT+0530 (India Standard Time)",
name: "Picture.png",
size: 860146,
type: "image/png",
webkitRelativePath: ""
}
When uploading files via an API, the files are sent within a FormData object. On a Node.js Express server, you can handle this incoming data using the Multer middleware. Here’s an example illustrating how to handle file uploads with Multer in Express, where I have used various file upload middlewares to store data in a dedicated folder based on certain conditions.
async function onFormSubmit(formValues: FormSchema) {
const formData = new FormData();
const { resume, pictures } = formValues;
/* resume can be null, hence handle the null check */
resume && formData.append('resume', resume);
Array.isArray(pictures) && pictures.forEach(file => {
formData.append('pictures', file);
});
await sendFormData(url, formData);
}
Advanced Usage
For more advanced scenarios, RHFFileUploader
can be configured to:
- Accept multiple files.
- Restrict file types using the
accept
prop, for example, to allow only images (image/*
). - Limit the maximum number of valid files a user can upload
- Use a custom upload button to match your design requirements.
- Customize the display of uploaded files, including file names, sizes, and a remove button.
<RHFFileUploader
fieldName="pictures"
control={control}
multiple
accept="image/*"
showFileSize
maxFiles={3}
maxSize={5 * 1024 * 1024}
label={
<Typography color="secondary" sx={{ fontWeight: 600 }}>
<CloudUploadIcon />
{` Upload Photos`}
</Typography>
}
renderUploadButton={fileInput => (
<div style={{ width: '200px' }}>
<IconButton component="label" tabIndex={-1}>
<UploadFileIcon />
{fileInput}
</IconButton>
</div>
)}
renderFileItem={(file, index) => (
<Typography variant="body2">
{index + 1}. {file.name}
{getFileSize(file.size, { precision: 2 })}
</Typography>
)}
onUploadError={(errors, rejectedFiles) => {
alert(`${rejectedFiles.length} file(s) were rejected as ${errors.join(' ,')}`)
}}
/>
The renderUploadButton
prop allows you to render a custom upload button,
with the fileInput
(the hidden file input) provided as its child.
Similarly, the renderFileItem
prop lets you customize how each uploaded
file is displayed in the file list.
Make sure to add the component="label"
prop to your custom
Button
or IconButton
component to ensure the file input is triggered correctly,
as file dialogs can only be opened via label elements or direct interaction with file inputs.
Additionally, add tabIndex={-1}
to the button to exclude it from the
tab order, keeping focus management limited to the hidden file input
itself for better accessibility.
Examples
API
The RHFFileUploader
accepts the following props:
Name | Type | Required | Description |
---|---|---|---|
fieldName | string | ✅ | React Hook Form requires name as a key for the registration process. This is a required prop for all components. |
control | UseFormControl | ✅ | The control option yielded on calling the useForm hook. |
registerOptions | RegisterOptions | Register options for validation if using react-hook-form without any validation libraries like yup or Joi. | |
required | boolean | Indicates that the field is mandatory by adding an asterisk symbol (*) to the formLabel . This visual cue helps users quickly identify required fields in the form. | |
accept | string | ✅ | The file types to accept in the file uploader component. Eg: image/* or .pdf,.docx . |
multiple | boolean | Allow selection of single or multiple values for a formfield. | |
maxFiles | number | The maximum number of files allowed to be uploaded in the file uploader component. Extra files will be rejected. | |
maxSize | number | The maximum file size in bytes allowed for each uploaded file. | |
showFileSize | boolean | Show the file size of the uploaded file(s) in the file uploader component. | |
hideFileList | boolean | Hide the list of files uploaded in the file uploader component. | |
onValueChange | (files: File OR File[] OR null) => void | An optional callback function that returns the file(s) uploaded in the file uploader component. | |
onUploadError | (errors: FileUploadError[], rejectedFiles: File[]) => void | Callback function that returns the error message and rejected files when uploaded files fail the validation during upload. | |
renderUploadButton | (fileInput: ReactNode) => ReactNode | Custom render function to replace the default upload button in the file uploader component. Refer to the example for more details. | |
renderFileItem | (file: File, index: number) => ReactNode | Custom render function to replace the default file item in the file uploader component. Refer to the example for more details. | |
disabled | boolean | A boolean value to enable or disable editing of the form field. | |
label | ReactNode | The text to render in FormLabel component. By default, the value of fieldName such as firstName will be transformed to display "First Name" using the fieldNameToLabel function. | |
showLabelAboveFormField | boolean | Render form label above the form field in FormLabel component. | |
formLabelProps | FormLabelProps | FormLabelProps to customise FormLabel component for a field. Multiple fields can be configured using the ConfigProvider component. | |
errorMessage | ReactNode | Error message to be shown for a field in FormHelperText component. | |
hideErrorMessage | boolean | A flag to prevent replacement of helper text of a field by the error message when the validation is triggered. | |
helperText | ReactNode | The content to display within the FormHelperText component below the field. If the field validation fails, this content will be overridden by the corresponding error message. | |
formHelperTextProps | FormHelperTextProps | FormHelperTextProps to customise FormHelperText component for a field. Multiple fields can be configured using the ConfigProvider component. | |
fullWidth | boolean | Set the width of the file uploader component to 100%. |