Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Wed May 10 2023

File input onChange not called second time the file is chosen

I was doing some work on our image resizer widget the other day, and I stumbled on an issue that I would like to share the solution to.

Problem statement

In my case, I was implementing a new feature for the widget that basically cleared the state of the component. Like the dimensions of the image, rotation and so on. But when I reselected the image, I found out that it didn't work if I selected the same as previously since my onChange callback was never called. So, why was that? And why is it working with another file? Basically, the <input /> is keeping the file in its value and will only fire the onChange if it is another value coming in. Let's fix this!

Solution

To fix this, we simply need to clear the value from the input after we are done with it.

Let's do a simple React implementation to show. In below code we will create a component which will have a state variable for the selected file, and if we have selected a file we will display the file name. In our onChange callback, we will set the selected file and when we are done, we will clear the input value to make sure our callback is called even if we choose the same file.

const FileInput = () => { const [selectedFile, setSelectedFile] = useState(null); const onFileSelected = (event) => { setSelectedFile(event.target.files[0]); // Additional logic should be performed here // When we are done, clear it event.target.value = ""; }; return ( <div style={{ display: "flex", flexDirection: "column" }}> {selectedFile?.name} <input type="file" onChange={onFileSelected} /> </div> ); };

Outro

In this short guide we showed how to solve an issue with file inputs not calling onChange when the same file is selected twice. This might not be a problem in many cases, but when we are using frameworks like React for example and are relying on state variables and not so much the actual input event values, it might be troublesome. Especially if we are also doing custom file inputs and not using the native elements, it can be even more usual to get these errors.

I hope you liked this article, and that it helped you.

All the best,

signatureWed May 10 2023
See all our articles