I want an event or get notified when the user clicks on the cross icon or the cancel button on the fileInput dialog so that I can perform some task based on this.
The onChange event is only triggered when the user clicks on Open Button.
Is there a way to get notified when the user clicks on a cross icon or cancel button using ReactJS?
Below is the working code snippet.
class Test extends React.Component {
constructor() {
super();
this.fileInputClicked = this.fileInputClicked.bind(this);
}
fileInputClicked(event){
let file = event.target.files[0];
console.log("File is Selected", file);
}
render() {
return (
<div>
<div>
<p>Hello world</p>
<input type="file" onChange={this.fileInputClicked}/>
</div>
</div>
);
}
}
ReactDOM.render(<Test/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app' />
Well, this is probably what I would do but I don't really like it, also I think that the whole idea of performing something because the user decided not to upload a file isn't a good user experience so use it wisely.
fileInputClicked(event){
let file = event.target.files[0];
console.log("File is Selected", file);
window.removeEventListener('focus', this.handleFocusBack);
}
handleFocusBack(){
console.log('focus-back');
window.removeEventListener('focus', this.handleFocusBack);
}
clickedFileInput(){
window.addEventListener('focus', this.handleFocusBack);
}
render() {
return (
<div>
<div>
<p>Hello world</p>
<input onClick={this.clickedFileInput} type="file" onChange={this.fileInputClicked}/>
</div>
</div>
);
}
This way, when the user decides to close the file input, he focuses back on the window and you get the handleFocusBack
functionality you want and when he adds a file he goes to the fileInputClicked
.
Afaik, there is no 'out of the box' mechanism to achieve what you want.