There are several issues in your code:
- On mount your
onChangeFile handler will be erased by the ref callback ref={(ref) => this.onChangeFile = ref}
- You're not binding any event handler on the
onchange event of your input.
It seems that what you are trying to do is to replace the ui of the file browser with a nice edit icon.
Html label element and its for attribute are there to help you.
The following snippet is plain html/js (no react) but will work in your component if you change the plain html for attribute for its React counter part htmlFor and if you bind the onChangeFile handler the jsx way that is
<input
type="file"
id="file"
onChange={this.onChangeFile}
style={{display: "none"}}
/>
Instead of document.getElementById('file').addEventListener('change', onChangeFile);
The refs are not needed here.
So to sum everything up:
- wrap you span icon into a
label element.
- set the
htmlFor attribute to the same value as the file input's id attribute.
- attach the onFileChange handler to the onChange event of the file input
That's it, the icon will act as your hidden input should.
onChangeFile = (event)=> {
console.log('event.target.files[0]', event.target.files[0])
event.stopPropagation();
event.preventDefault();
var file = event.target.files[0];
console.log('file.....:', file);
}
document.getElementById('file').addEventListener('change', onChangeFile);
.edit-icon {
display: inline-block;
width: 20px;
height: 20px;
background-color: #EEAA11;
}
<label for="file"><span class='fa fa-edit edit-icon'> </span><label>
<input type="file" id="file" style="display: none;"/>