I have a component which uses <input type="file" value="" onChange={(e) => callback(e.target.files}/> to get user selected files. But if user cancels the file selection popup, the callback will never be called since there is no change. This is nonsense, since the expected action is callback gets called with null or empty array.
But how to implement this? I didn't find any related event to listen.
you can store the callback call in a variable example let isCalled = false than in your callback set it to true,
and check it then do what need to do. Maybe it is bad practice but as an option...
@seriouslyfluffy not quite clear about your solution. for a robust lib, user should always be notified whether the process succeeded or failed. for example, the window.confirm function will return null if user click cancel. if we make a async version of confirm, the callback should always be called.
@zhaoyao91 how about this one http://jsfiddle.net/Shiboe/yuK3r/6/
try this
<input type="file" value="" onChange={(e) => {
const { target } = e
if(target.value.length > 0){
callback(target.files)
} else {
target.reset();
}
} />
@seriouslyfluffy hi, one more question, if i trigger the callback on body's focus event, how to get the files user selected? by my test, the focus event is triggered before input's change event
@zhaoyao91 in example what i showed, you can access to files via godzilla.files it is array FilesList
File inputs don't expose cancellation events. If there was already a selection made, it will call onChange if the file selector is opened again and canceled (what @passapol-e's solution addresses).
Also, for future reference: we try to use this issue tracker for bug reports and feature requests only. If you have a usage or support question, we recommend checking out one of the great community-driven platforms like Reactiflux, discuss.reactjs.org, or StackOverflow.
When we select the file following events are called -
Scenario 1 : When the select file is clicked and then cancel is clicked
Focus event value=""
Click event value=""
Blur event value=""
Focus event value=""
Blur event value="" (when the user clicks somewhere out)
Scenario 2 : When the file is selected -
Focus event value=""
Click event value=""
Blur event value=""
Focus event value=""
Change event value="filevalue"
Blur event value="filevalue"
Focus event value="filevalue"
Blur event value="filevalue" (when the user clicks somewhere out)
We see here, when the Blur event (last event) is called after focus event with no value of file means that the Cancel button is clicked.
My scenario was to change the Submit button text to "Please wait" while the file is loading currentEvent variable is used to hold the current event value either click or focus if the currentEvent = focus and file value is null means Cancel button is clicked.
````
HTML Code
accept=".csv,.xlsx,.xlsb" onChange='onFileBrowse()' onclick="fileClick()" onfocus="fileFocus()" onblur="fileBlur()" />
`
Most helpful comment
try this