ArbitB ArbitB - 7 months ago 31
React JSX Question

onChange method not getting called from input

I am having a button from which I open the file explorer. I am doing it like this

{
this.props.fileUploadIsOpen
&& <div className='assign-dialog'>
<div className='assign-dialog-inner'>
<div className='dia-title'> File Upload</div>
<div className='dia-body'>
<div className='control-container'>
<div className='control-label'> Video File</div>
<div className='control'>
<input type="text" className="form-control" id="usr"/>
<button type="button" className="btn btn-primary" onClick={(e) => this.upload.click()}>Browse</button>
<input id="myInput" type="file" ref={(ref) => this.upload = ref} style={{visibility: 'hidden', width:0}} onChange={this.handleFileSelect}/>
</div>
</div>


But onChange method is not getting called. When I select a file, nothing happens. onChange method is supposed to called handleFileSelect function, which prints the file name in console. But nothing happens in console. Is onChange not getting triggered? How can I solve it?

Answer Source

I do not know why you are passing a function to the ref attr, but I have recreated your case and it nails what you want

class Uploader extends React.Component {
    constructor () {
        super();
    }

    onClick (e) {
        const {fileUpload} = this.refs;
        fileUpload.click();
    }
    // prints the file name
    handleFileSelect (e) {
        const {fileUpload} = this.refs;
        console.log(fileUpload.files[0].name)
    }
    render () {
        return (
            <div>
                <div className='control-label'> Video File</div>
                <div className='control'>
                    <input type="text" className="form-control" id="usr"/>
                    <button 
                    type="button" 
                    className="btn btn-primary" 
                    onClick={this.onClick.bind(this)}>Browse</button>
                    <input id="myInput" type="file" ref="fileUpload" style={{visibility: 'hidden', width:0}} onChange={this.handleFileSelect.bind(this)}/>
                </div>
            </div>
        );
    }
}