Sub topic 13
File inputs
This chapter assumes you know controlled inputs, useState, event handlers, and FormData from the earlier chapters. It covers why <input type="file"> is the one form control React cannot control, and how to work with it anyway.
Why file inputs are always uncontrolled
A controlled input takes its displayed value from state through the value prop. A file input cannot work this way. Browsers do not let a script set the selected file path, because that would let a page choose files from the user's disk without the user's action. The only way a file gets into the input is through the user's file picker or a drag and drop.
So a file input is always uncontrolled. React will warn or throw if you try to give it a value.
// Wrong: React cannot set the value of a file input.
<input type="file" value={file} onChange={handleChange} />You can still attach onChange and read the selection, but the DOM owns the value. You can also keep a copy of the selected files in state, which is the usual way to show previews, file names, and validation messages.
Reading the selected files
When the user picks files, the input fires a change event. The selected files are in e.target.files, a FileList. A FileList is array-like but not an array, so convert it with Array.from or spread syntax before using map or filter.
Each item is a File object with these useful properties:
| Property | Meaning |
|---|---|
| `name` | The file name, without the path |
| `size` | Size in bytes |
| `type` | MIME type reported by the browser, such as `image/png`. It can be an empty string. |
| `lastModified` | Timestamp in milliseconds |
import { useState } from 'react';
export default function FilePicker() {
const [files, setFiles] = useState([]);
function handleChange(e) {
setFiles(Array.from(e.target.files));
}
return (
<div>
<label htmlFor="docs">Choose documents</label>
<input id="docs" type="file" multiple onChange={handleChange} />
<ul>
{files.map((file) => (
<li key={`${file.name}-${file.lastModified}`}>
{file.name} ({(file.size / 1024).toFixed(1)} KB)
</li>
))}
</ul>
</div>
);
}The multiple attribute lets the user select more than one file. Without it, files holds at most one item. The key combines the name and lastModified because two selected files can share a name when they come from different folders, and even that pair is not guaranteed unique. For a list that never reorders, this is acceptable.
The state here holds the File objects, not the input's value. The input still displays its own selection. If you clear the state, the input does not clear itself. That mismatch is the main source of bugs, covered below.
Restricting and validating files
The accept attribute filters what the picker shows. It takes a comma-separated list of extensions, MIME types, or wildcards.
<input type="file" accept="image/png, image/jpeg, .webp" />accept is a hint. Users can often switch the picker to "All files", and drag and drop can bypass it. Always validate in code, and validate again on the server.
import { useState } from 'react';
const MAX_BYTES = 2 * 1024 * 1024;
const ALLOWED = ['image/png', 'image/jpeg'];
function checkFile(file) {
if (!ALLOWED.includes(file.type)) {
return 'Only PNG and JPEG images are allowed.';
}
if (file.size > MAX_BYTES) {
return 'The image must be 2 MB or smaller.';
}
return null;
}
export default function AvatarField() {
const [file, setFile] = useState(null);
const [error, setError] = useState(null);
function handleChange(e) {
const selected = e.target.files[0];
if (!selected) {
setFile(null);
setError(null);
return;
}
const problem = checkFile(selected);
setError(problem);
setFile(problem ? null : selected);
}
return (
<div>
<label htmlFor="avatar">Avatar</label>
<input
id="avatar"
type="file"
accept="image/png, image/jpeg"
onChange={handleChange}
aria-invalid={Boolean(error)}
aria-describedby={error ? 'avatar-error' : undefined}
/>
{error && <p id="avatar-error">{error}</p>}
{file && <p>Ready: {file.name}</p>}
</div>
);
}This follows the same pattern as the validation chapter: a pure function returns a message or nothing, and the message is tied to the input with aria-describedby. The file.type value comes from the browser's guess based on the extension, so a renamed file can report the wrong type. Server-side checks of the actual bytes are the real defense.
Note the case where the user opens the picker and cancels. Browsers differ: some clear the previous selection and fire change with an empty FileList, and others keep the old one and fire nothing. Handling the empty case, as the code above does, keeps your state in step with whatever the input reports.
Previewing an image
To show a preview, create a temporary URL for the file with URL.createObjectURL. The URL points at the file in memory and stays alive until you release it with URL.revokeObjectURL. Skipping the release leaks memory for the life of the page.
An effect is the right place for this, because creating and revoking the URL is a side effect that needs cleanup.
import { useEffect, useState } from 'react';
export default function ImagePreview() {
const [file, setFile] = useState(null);
const [previewUrl, setPreviewUrl] = useState(null);
useEffect(() => {
if (!file) {
setPreviewUrl(null);
return undefined;
}
const url = URL.createObjectURL(file);
setPreviewUrl(url);
return () => URL.revokeObjectURL(url);
}, [file]);
return (
<div>
<label htmlFor="photo">Photo</label>
<input
id="photo"
type="file"
accept="image/*"
onChange={(e) => setFile(e.target.files[0] ?? null)}
/>
{previewUrl && <img src={previewUrl} alt="Selected upload preview" width="160" />}
</div>
);
}The cleanup function runs before the effect re-runs and when the component unmounts, so every URL is revoked exactly once. In development with React Strict Mode, effects run twice on mount, which is why the cleanup matters: without it you would create an extra URL each time.
Uploading with FormData
The FormData chapter showed reading a form on submit. For files it does more: it builds a multipart/form-data body, the format servers expect for uploads. Pass the FormData object directly as the fetch body.
import { useState } from 'react';
export default function UploadForm() {
const [status, setStatus] = useState('idle');
async function handleSubmit(e) {
e.preventDefault();
const data = new FormData(e.currentTarget);
setStatus('uploading');
try {
const response = await fetch('/api/upload', {
method: 'POST',
body: data,
});
if (!response.ok) throw new Error(`Upload failed: ${response.status}`);
setStatus('done');
} catch (err) {
console.error(err);
setStatus('error');
}
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="title">Title</label>
<input id="title" name="title" defaultValue="" />
<label htmlFor="attachment">Attachment</label>
<input id="attachment" name="attachment" type="file" />
<button type="submit" disabled={status === 'uploading'}>
{status === 'uploading' ? 'Uploading...' : 'Upload'}
</button>
{status === 'done' && <p role="status">Upload complete.</p>}
{status === 'error' && <p role="alert">Upload failed. Try again.</p>}
</form>
);
}Two details matter here:
- Do not set a
Content-Typeheader yourself. The browser must generate it, because the header includes a boundary string that separates the parts of the body. Setting it by hand omits the boundary and the server cannot parse the request. - The file input needs a
nameattribute.FormDataskips inputs with no name, so the file would be missing from the request.
If the user submits with no file chosen, the field is still included, as an empty File with a size of 0 and an empty name. Check data.get('attachment').size on the client if a file is required.
Resetting a file input
Because state and the input can drift apart, resetting needs care. Clearing state does not clear the displayed file name. There are two reliable approaches.
The first is to reset the whole form. form.reset() clears file inputs along with every other uncontrolled field.
e.currentTarget.reset();The second is to change the input's key. A new key makes React create a new DOM element, which starts empty. This works when the input is not inside a form you can reset, or when you want to clear only the file field.
import { useState } from 'react';
export default function ClearableFile() {
const [file, setFile] = useState(null);
const [inputKey, setInputKey] = useState(0);
function handleClear() {
setFile(null);
setInputKey((k) => k + 1);
}
return (
<div>
<label htmlFor="report">Report</label>
<input
key={inputKey}
id="report"
type="file"
onChange={(e) => setFile(e.target.files[0] ?? null)}
/>
{file && (
<button type="button" onClick={handleClear}>
Remove {file.name}
</button>
)}
</div>
);
}The key trick is the same one used earlier to reset a form when the record changes. A third option, writing to a ref with inputRef.current.value = '', also works, but the key approach keeps the logic inside React's data flow.
Common errors
- Passing
valueto a file input. React cannot honor it and the browser throws. Remove it and reade.target.files. - Using
files.mapdirectly.FileListhas nomap. Convert withArray.from(e.target.files). - Forgetting
name. The file is missing fromFormDataand from the request. - Setting
Content-Typeon a multipart request. The boundary is lost and the server rejects the body. - Trusting
acceptorfile.type. Both are advisory. Enforce limits on the server. - Not revoking object URLs. Each unreleased preview URL holds the file in memory.
- Selecting the same file twice. Choosing the same file again does not fire
change, because nothing changed. If you let users re-pick after a rejected file, clear the input (with thekeyapproach) so the retry registers.
Exercise
A user picks a 5 MB image in your avatar field. Your handleChange rejects it with an error and sets file state to null, but the input still shows the file name. The user then picks the same file again and nothing happens. Why does this occur, and how do you fix it?
Show answer
The file input is uncontrolled, so setting state to null does not clear what the input displays. Because the input's own value never changed, picking the same file again fires no change event. Fix it by clearing the DOM input when you reject the file: increment a key on the input so React mounts a fresh, empty element (or set e.target.value = '' in the handler). Show the error message so the user knows why the file was dropped.
Exercise
Your upload form posts a FormData body with fetch, and the server reports that it cannot find the uploaded file or parse the body. Name two causes you would check.
Show answer
First, the file input may have no name attribute, so FormData leaves it out. Second, the code may set a Content-Type: multipart/form-data header by hand, which removes the boundary the browser would have added. Remove the header and add name to the input.