Sub topic 13
File inputs
This chapter assumes you know controlled inputs (value plus onChange), useState, useEffect, and preventDefault on submit. It also uses FormData, which was covered earlier.
Why file inputs are different
A text input is controlled when React supplies its value. An <input type="file"> can't work that way. Browsers don't let a script set the selected file, because a page could otherwise pick files off the user's disk. Passing a value to a file input does not select a file. Only the user can choose one.
A file input is therefore always uncontrolled. The DOM holds the selection, and React reads it when needed. The onChange handler still works, and it is the usual place to copy the selection into state.
Reading the selected file
When the user picks files, e.target.files is a FileList. It is array-like but not an array. Each item is a File object with name, size, type and lastModified.
import { useState } from 'react';
export default function SingleFilePicker() {
const [file, setFile] = useState(null);
function handleChange(e) {
setFile(e.target.files[0] ?? null);
}
return (
<div>
<label>
Choose a file
<input type="file" onChange={handleChange} />
</label>
{file && (
<p>
{file.name} ({Math.round(file.size / 1024)} KB, {file.type || 'unknown type'})
</p>
)}
</div>
);
}The ?? null handles the case where the user opens the dialog and cancels. The list can then be empty. For <input type="file" multiple>, use Array.from(e.target.files) to get a real array you can map over.
Preview, upload and clear
The next component combines the three jobs you usually need. It shows an image preview, uploads with FormData, and clears the selection.
import { useEffect, useRef, useState } from 'react';
export default function AvatarUpload() {
const [file, setFile] = useState(null);
const [previewUrl, setPreviewUrl] = useState(null);
const inputRef = useRef(null);
useEffect(() => {
if (!file) {
setPreviewUrl(null);
return;
}
const url = URL.createObjectURL(file);
setPreviewUrl(url);
return () => URL.revokeObjectURL(url);
}, [file]);
function handleChange(e) {
setFile(e.target.files[0] ?? null);
}
async function handleSubmit(e) {
e.preventDefault();
if (!file) return;
const body = new FormData();
body.append('avatar', file);
await fetch('/api/avatar', { method: 'POST', body });
}
function handleClear() {
setFile(null);
inputRef.current.value = '';
}
return (
<form onSubmit={handleSubmit}>
<label>
Avatar
<input
ref={inputRef}
type="file"
accept="image/*"
onChange={handleChange}
/>
</label>
{previewUrl && <img src={previewUrl} alt="Selected avatar preview" width="96" />}
<button type="submit" disabled={!file}>Upload</button>
<button type="button" onClick={handleClear}>Clear</button>
</form>
);
}Three details matter here:
URL.createObjectURLcreates a temporary URL that points at the file in memory. It stays allocated until you callURL.revokeObjectURL, so the effect's cleanup function does that when the file changes or the component unmounts.- Clearing the state does not clear the input. The input still shows the old file name until you set
inputRef.current.value = ''. This is the one place where writing to a file input'svalueis allowed, and only with an empty string. - Don't set a
Content-Typeheader yourself when sendingFormDatawithfetch. The browser addsmultipart/form-dataalong with the required boundary string. A hand-written header leaves the boundary out, and the server can't parse the body.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Warning about changing an input from uncontrolled to controlled | A `value` prop was passed to the file input | Remove `value` and read `e.target.files` |
| Selecting the same file twice does not fire `onChange` | The input's value did not change | Reset `inputRef.current.value = ''` after handling the file |
| Server receives an empty body | Manual `Content-Type` header, or the field has no `name` in a native form | Let the browser set the header and use the right field name |
| Memory grows with many previews | Object URLs never revoked | Revoke them in the effect cleanup |
Exercise
A user picks a photo, clicks your Clear button, and the preview disappears, but the input still shows the old file name. Which line is missing from handleClear, and why can't you fix this with a value prop?
Show answer
Add inputRef.current.value = '' (with a ref attached to the input) after setFile(null). A file input is always uncontrolled because browsers forbid scripts from setting the selected file, so React can't drive it through a value prop. Only an empty string can be assigned to clear it.