File Inputs: Always Uncontrolled
What you'll learn: Why file input elements in React must always be uncontrolled and how to work with them using refs.
The Security Restriction
Unlike text inputs, checkboxes, and selects, file inputs cannot be controlled in React. You cannot set a value prop to programmatically choose which file appears in the input. This isn't a React limitation—it's a browser security feature. JavaScript cannot set file paths for security reasons (imagine a malicious script silently selecting sensitive files from your computer!).
Always Use Refs with File Inputs
Because you can't control file inputs with state, you must access them with refs:
function FileUpload() {
const fileInputRef = useRef(null);
function handleSubmit(event) {
event.preventDefault();
const selectedFiles = fileInputRef.current.files;
console.log('Selected file:', selectedFiles[0]);
}
return (
<form onSubmit={handleSubmit}>
<input type="file" ref={fileInputRef} />
<button type="submit">Upload</button>
</form>
);
}
The files property on the input element gives you access to a FileList object containing the selected file(s).
The Analogy
Think of a file input like a locked safe that only the user can open. React can observe what's inside (read the files using refs), but it cannot put files into the safe itself. The user must physically select files through the browser's file picker dialog.
No value Prop, No Problem
You can still use defaultValue or leave it alone entirely—most file inputs simply start empty. The browser handles the file selection UI, and you read the results when needed (typically on form submit).
Key Takeaway: File inputs must always be uncontrolled in React due to browser security restrictions; use refs to access the files property when you need to read selected files.