Skip to Content
Piplup
@piplup/rhf-adaptersmui-file-inputComponents

MuiFileInputElement

Use mui-file-input with react-hook-form: MuiFileInputElement stores a File or File[], with file size and type validation.

MuiFileInputElement renders MuiFileInput from mui-file-input and stores the selected file in React Hook Form: a File (or null) by default, or a File[] when multiple is set. To build your own file field, use useMuiFileInputAdapter.

Import

import { MuiFileInputElement } from '@piplup/rhf-adapters/mui-file-input';

Usage

'use client';import Stack from '@mui/material/Stack';import { MuiFileInputElement } from '@piplup/rhf-adapters/mui-file-input';import { MuiButtonElement } from '@piplup/rhf-adapters/mui-material';import { useForm } from 'react-hook-form';export default function Page() {  const { control, handleSubmit } = useForm({    defaultValues: { resume: null },  });  return (    <form onSubmit={handleSubmit((values) => alert(JSON.stringify(values, null, 2)))}>      <Stack direction="column" spacing={2}>        <MuiFileInputElement control={control} label="Resume" name="resume" />        <div>          <MuiButtonElement control={control} type="submit" variant="contained">            Submit          </MuiButtonElement>        </div>      </Stack>    </form>  );}

JSON.stringify turns a File into {}, which is why the alert above shows an empty object. Read name, size and type from the File instead, or append it to a FormData to upload it.

Validating files

The element has no size or type options of its own. Write those checks as rules.validate functions; they receive the File or File[] from the form. This demo accepts up to three images of 1 MB or less, and the Reset button clears the selection.

'use client';import Button from '@mui/material/Button';import Stack from '@mui/material/Stack';import { MuiFileInputElement } from '@piplup/rhf-adapters/mui-file-input';import { MuiButtonElement } from '@piplup/rhf-adapters/mui-material';import { useForm } from 'react-hook-form';const MAX_SIZE = 1024 * 1024; // 1 MBtype FormValues = { photos: File[] };export default function Page() {  const { control, handleSubmit, reset } = useForm<FormValues>({    defaultValues: { photos: [] },  });  return (    <form      onSubmit={handleSubmit((values) =>        // File objects serialize to {} with JSON.stringify, so list them by hand.        alert(          values.photos            .map((file) => `${file.name} (${Math.round(file.size / 1024)} KB)`)            .join('\n'),        ),      )}      noValidate    >      <Stack direction="column" spacing={2}>        <MuiFileInputElement          rules={{            validate: {              count: (files) => files.length <= 3 || 'Attach up to 3 photos',              size: (files) =>                files.every((file) => file.size <= MAX_SIZE) ||                'Each photo must be 1 MB or smaller',              type: (files) =>                files.every((file) => file.type.startsWith('image/')) ||                'Only image files are allowed',            },          }}          control={control}          label="Photos"          messages={{ required: 'Attach at least one photo' }}          name="photos"          placeholder="Choose up to 3 images"          // `accept` only filters the browser's file picker. The rules below enforce it.          slotProps={{ htmlInput: { accept: 'image/*' } }}          multiple          required        />        <Stack direction="row" spacing={1}>          <MuiButtonElement control={control} type="submit" variant="contained">            Upload          </MuiButtonElement>          <Button onClick={() => reset()} variant="outlined">            Reset          </Button>        </Stack>      </Stack>    </form>  );}

slotProps.htmlInput.accept only filters what the browser's file picker shows. Users can still choose "All files", so keep a type check in your rules.

How it works

Single vs. multiple. Without multiple, the form value is a File, or null when nothing is selected or the clear button is pressed. With multiple, it is always an array: [] when empty. A value that isn't an array (for example undefined from missing defaultValues) is shown as [] in multiple mode and as null otherwise.

Set multiple on the element, not through slotProps.htmlInput.multiple. With the latter, the browser lets users pick several files but only the first one is stored.

Rules. required fails for null and for an empty array, with the default message "Please fill out this field." Text rules (minLength, maxLength, min, max, pattern) are not supported. To limit the number of files, check files.length in rules.validate.

Resetting. reset() or setValue(name, null) clears the field, and the element also clears the underlying <input type="file">, so the same file can be chosen again afterwards.

Errors and helper text. While the field is invalid, its error message replaces helperText.

Refs. inputRef is merged with React Hook Form's ref. A ref on the element goes to the MuiFileInput root.

Props

Prop

Type

useMuiFileInputAdapter

useMuiFileInputAdapter connects a field to React Hook Form and returns the props MuiFileInputElement spreads onto its component. Use it to build your own field on the same wiring, for example with different markup around the input.

Import

import { useMuiFileInputAdapter } from '@piplup/rhf-adapters/mui-file-input';
import * as React from 'react';import { MuiFileInput } from 'mui-file-input';import { useMuiFileInputAdapter } from './adapter';import type { UseMuiFileInputAdapterProps, MuiFileInputValue } from './adapter';import type { Transform } from '@piplup/rhf-core';import type { MuiFileInputProps } from 'mui-file-input';import type { FieldPath, FieldValues } from 'react-hook-form';export type MuiFileInputElementProps<  Multiple extends boolean | undefined = undefined,  TTransformedValue extends MuiFileInputValue<Multiple> = MuiFileInputValue<Multiple>,  TFieldValues extends FieldValues = FieldValues,  TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,> = Omit<  MuiFileInputProps,  'checked' | 'defaultChecked' | 'defaultValue' | 'name' | 'style' | 'value'> &  Omit<    UseMuiFileInputAdapterProps<Multiple, TTransformedValue, TFieldValues, TName>,    'composeHelperText' | 'onBlur' | 'onChange' | 'transform'  > & {    /**     * Transformation functions for the field's input and output values.     */    transform?: Transform<MuiFileInputProps['onChange'], TTransformedValue, TFieldValues, TName>;  };function MuiFileInputComponent<  Multiple extends boolean | undefined = undefined,  TTransformedValue extends MuiFileInputValue<Multiple> = MuiFileInputValue<Multiple>,  TFieldValues extends FieldValues = FieldValues,  TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,>(  props: MuiFileInputElementProps<Multiple, TTransformedValue, TFieldValues, TName>,  ref?: MuiFileInputProps['ref'],): React.ReactElement {  const {    className,    control,    defaultValue,    disabled,    disableOnError,    disableOnIsSubmitting,    error,    errorParser,    helperText,    inputRef,    messages,    multiple,    name,    onBlur,    onChange,    required,    rules,    shouldUnregister,    style,    transform,    ...rest  } = props;  const adapter = useMuiFileInputAdapter(    {      className,      composeHelperText: true,      control,      defaultValue,      disabled,      disableOnError,      disableOnIsSubmitting,      error,      errorParser,      helperText,      inputRef,      messages,      multiple,      name,      onBlur,      onChange,      required,      rules,      shouldUnregister,      style,      transform,    },    ref,  );  const inputProps = { ...rest, ...adapter } as MuiFileInputProps;  return <MuiFileInput {...inputProps} />;}export const MuiFileInputElement = React.forwardRef(  MuiFileInputComponent,) as typeof MuiFileInputComponent & { displayName?: string };if (process.env.NODE_ENV !== 'production') {  MuiFileInputElement.displayName = 'MuiFileInputElement';}

Props

Prop

Type

Return value

  • Return value: adapter props including value, multiple, onChange, onBlur, inputRef, error, and helperText.

Notes

  • Use this hook when your file picker UI is custom but should still be RHF-aware.
  • It builds on useControllerAdapter.

On this page