const [file, setFile] = useState(null);
<Grid xs={8}>
<Typography sx={{ fontWeight: 'bold' }}>Upload File</Typography>
<FormControl size="small" sx={{ mr: 2 }}>
<Button component="label" variant="contained">Choose File
<input
type="file"
hidden
required
accept=".pdf,image/gif,image/jpeg,image/png,image/tiff"
/>
</Button>
</FormControl>
{file && <FormLabel>{file.name}</FormLabel>}
</Grid>
I want to integrate react-hook-form with my custom mui file upload button. When a file is selected, the file name will be displayed next to the button.
After studying the react-hook-form documentation, I use Controller
to register the component and updated codes are shown below.
const { control } = useForm();
<Grid xs={8}>
<Typography sx={{ fontWeight: 'bold' }}>Upload File</Typography>
<FormControl size="small" sx={{ mr: 2 }}>
<Controller
name="file"
control={control}
render={({ field }) => (
<Button component="label" variant="contained">Choose File
<input
{...field}
type="file"
hidden
required
accept=".pdf,image/gif,image/jpeg,image/png,image/tiff"
/>
</Button>
)
/>
</FormControl>
{file && <FormLabel>{file.name}</FormLabel>}
</Grid>
However, when a file is selected, the file name can’t be displayed. I asked Poe and it gives me following two sets of codes.
Set 1:
const [fileName, setFileName] = useState("");
useEffect(() => {
if (field.value?.[0]) {
setFileName(field.value[0].name);
} else {
setFileName('');
}
}, [field.value]);
<Grid xs={8}>
<Typography sx={{ fontWeight: 'bold' }}>Upload File</Typography>
<FormControl size="small" sx={{ mr: 2 }}>
<Controller
name="file"
control={control}
render={({ field }) => (
<Button component="label" variant="contained">Choose File
<input
{...field}
type="file"
hidden
required
accept=".pdf,image/gif,image/jpeg,image/png,image/tiff"
/>
</Button>
)
/>
</FormControl>
<FormLabel>{fileName}</FormLabel>
</Grid>
Set 2:
const [fileName, setFileName] = useState("");
const { control, register } = useForm();
useEffect(() => {
if (register('file').value?.[0]) {
setFileName(register('file').value[0].name);
} else {
setFileName('');
}
}, [register('file').value]);
<Grid xs={8}>
<Typography sx={{ fontWeight: 'bold' }}>Upload File</Typography>
<FormControl size="small" sx={{ mr: 2 }}>
<Controller
name="file"
control={control}
render={({ field }) => (
<Button component="label" variant="contained">Choose File
<input
{...field}
type="file"
hidden
required
accept=".pdf,image/gif,image/jpeg,image/png,image/tiff"
/>
</Button>
)
/>
</FormControl>
<FormLabel>{fileName}</FormLabel>
</Grid>
However, neither sets of codes work. Are my codes of using Controller
wrong? How can the file name be displayed?