Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React input type file onChange not firing

Using React v16.1, on a local development server. I have a simple component to upload a file here:

class FileImporter extends React.Component {
    constructor(props) {...}
    importFile(e) {
      // import the file here, not firing
    }
    render() {
      return (<input type="file" onChange={this.importFile.bind(this)} />);
    }
}    

The function importFile never fires. I've tried binding onChange in the following ways:

onChange={e => this.importFile(e)}
onChange={this.importFile.bind(this)}
onChange={this.importFile}

I've tried using react-file-reader-input and react-file-reader, and just a raw input tag like in the snippet. None of them fire the onChange handler. The system file upload dialog shows up, but on selecting a file nothing happens. How can I get the onChange event to fire?

like image 481
Srivathsan Jayaraman Avatar asked May 11 '18 21:05

Srivathsan Jayaraman


2 Answers

For others who google here: I had a similar issue and the solution I found was that my <input> was being removed from the DOM after clicking the button to open the file picker. (It was inside a drop down.)

Clicking the input still showed the file picker, but that also caused the drop down to hide, thus removing the input from the DOM. After selecting a file the onChange never fired. I moved the input to a place that it wouldn't be removed from the DOM and things began to work again.

like image 191
user3788955 Avatar answered Oct 07 '22 14:10

user3788955


Use onInput instead of onChange

                <div className="profile-form-buttons centercontents">
                    <input className="form-compo"
                        type="file" 
                        name="file-uploader" 
                        id="file-uploader"  
                        onInput={imageUpdate}
                        style={{display:"none"}}
                        />
                </div>
like image 41
Mars Araullo Avatar answered Oct 07 '22 15:10

Mars Araullo