While working with file uploads in React, you may encounter an issue where selecting a file, modifying it from file explorer, and then picking it again does not trigger the onChange
event. This can be frustrating, especially when handling file validation or re-uploads. The root cause is that browsers do not fire onChange
if the same file (by name) is selected again.
Let's consider a common React file input implementation:
<input type="file" onChange={(e) => handleFileUpload(e.target.files[0])} />
At first, everything works fine:
- A user selects
document.pdf
, and theonChange
event fires. - The file is uploaded, but the server rejects it due to invalid content.
- The user modifies
document.pdf
and selects it again. - Nothing happens! The
onChange
event does not trigger.
Browsers optimize file inputs by not triggering onChange
if the selected file has the same name and path as the previous selection. Since document.pdf
remains the same filename, the event does not fire, causing the issue.
To ensure the onChange
event fires even when selecting the same file, we can reset the input field on click:
<input
type="file"
onClick={(e) => (e.target.value = null)}
onChange={(e) => handleFileUpload(e.target.files[0])}
/>
- The
onClick
event resets the input value before selecting the file again (e.target.value = null
), ensuring that even if the user selects the same file, theonChange
event will trigger. - The
onChange
handler then properly processes the newly selected file.
Another way to solve this is by resetting the value inside onChange
:
<input
type="file"
onChange={(e) => {
if (!e.target.files.length) return;
handleFileUpload(e.target.files[0]);
e.target.value = ""; // Reset after handling file
}}
/>
If you are using Axios for file uploads, this issue can also cause a misleading Network Error
. This could be due to React state still holding a reference to the previously selected file, which has already been modified. Axios may not receive the correct file reference, leading to an error response.
Example error message:
{
"message": "Network Error",
"name": "AxiosError",
"stack": "AxiosError: Network Error at XMLHttpRequest.handleError...",
"config": {...},
"code": "ERR_NETWORK"
}
If you're dealing with file uploads in React (or vanilla JavaScript) and notice that selecting the same file twice doesn't trigger onChange
, resetting the input field value is a simple and effective fix. Adding e.target.value = null
to onClick
ensures smooth re-selection and prevents unexpected behavior in file upload forms. Additionally, this fix can help prevent Axios network errors caused by stale file references in state.
Happy coding! 🚀