Handling File Inputs on Submit
You'll learn how to read uploaded files from uncontrolled file inputs when a form is submitted.
Why File Inputs Are Special
File inputs in React are always uncontrolled—you cannot set their value programmatically for security reasons. The browser strictly controls what files a user selects. Your job is to read those File objects when the form submits, not control them beforehand.
Reading Files with Refs
The most straightforward approach uses a ref attached to the file input:
function FileUploadForm() {
const fileInputRef = useRef(null);
function handleSubmit(event) {
event.preventDefault();
const files = fileInputRef.current.files;
// files is a FileList object (array-like)
if (files.length > 0) {
const firstFile = files[0];
console.log('File name:', firstFile.name);
console.log('File size:', firstFile.size);
console.log('File type:', firstFile.type);
}
}
return (
<form onSubmit={handleSubmit}>
<input type="file" ref={fileInputRef} />
<button type="submit">Upload</button>
</form>
);
}
The .files property gives you a FileList containing all selected File objects.
Reading Files with FormData
Alternatively, use the FormData API to extract files by name:
function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
const uploadedFile = formData.get('avatar'); // matches input's name attribute
console.log(uploadedFile.name);
}
// In JSX:
<input type="file" name="avatar" />
This approach works seamlessly when you're already using FormData to collect other form fields.
Key Takeaway: File inputs are always uncontrolled—read the File objects from inputRef.current.files or via FormData when the form submits, then process them as needed (validation, upload, preview, etc.).