useFileDialog
useFileDialog validates the files chosen in an <input type="file">. It returns an onChange handler that hands
the files to onFilesSelect when every file matches accept (all files when accept is omitted), or reports the first mismatch to
onUnsupportedFile.Hooks
Signature
const { getFiles } = useFileDialog({ accept, onFilesSelect, onUnsupportedFile });Name | Type | Description |
|---|---|---|
accept | string[] | Accepted types, as in the HTML accept attribute. Omit to accept all. |
onFilesSelect | (f: File[]) => void | Receives the selected files when all of them are accepted. |
onUnsupportedFile | (f: File) => void | Receives the first file that does not match; nothing is selected. |
single | boolean | Validates and delivers only the first file. |
returns | { getFiles } | Pass getFiles as the input's onChange. |
Scrolls sideways inside the table. The page does not.
Example
import { useFileDialog } from '@apollion-dsi/core/hooks';
function FilePicker({ onFiles }: { onFiles: (files: File[]) => void }) {
const { getFiles } = useFileDialog({
accept: ['image/*'],
onFilesSelect: onFiles,
onUnsupportedFile: (file) => alert(`Unsupported type: ${file.name}`),
});
return <input type="file" accept="image/*" multiple onChange={getFiles} />;
}Pitfalls
- Pass the same
acceptlist to the input'sacceptattribute too, so the browser filters the picker. - One unsupported file rejects the whole selection.
- The input value is cleared after each change, so picking the same file again fires again.