I have been working on creating a custom <input type="file">
upload button in React. My goal is to display the name of the uploaded file on the button itself after the upload. I encountered some challenges while trying to create a codepen demo, so I will just share the code here instead. Apologies for any inconvenience.
import React, { Component, PropTypes } from 'react';
import './InputFile.css';
export default class InputFile extends Component {
constructor(props: any)
{
super(props);
this.getUploadedFileName = this.getUploadedFileName.bind(this);
}
getUploadedFileName(selectorFiles: FileList, props) {
const { id } = this.props;
;( function ( document, window, index )
{
var inputs = document.querySelectorAll(`#${id}`);
Array.prototype.forEach.call( inputs, function( input )
{
var label = input.nextElementSibling,
labelVal = label.innerHTML;
input.addEventListener( 'change', function( e )
{
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) ||
'' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName )
label.querySelector( 'span' ).innerHTML = fileName;
else
label.innerHTML = labelVal;
});
// Firefox bug fix
input.addEventListener( 'focus', function(){ input.classList.add(
'has-focus' ); });
input.addEventListener( 'blur', function(){ input.classList.remove(
'has-focus' ); });
});
}( document, window, 0 ));
}
render () {
const { id, text, multiple } = this.props;
return(
<div>
<input id={id} type="file" className="km-btn-file" data-multiple-caption="{count} files selected" multiple={multiple} onChange={ (e, id) => this.getUploadedFileName(e.target.files, id)}></input>
<label htmlFor={id} className="km-button km-button--primary km-btn-file-label">
<span>{text}</span>
</label>
</div>
);
}
}
InputFile.propTypes = {
id: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
multiple: PropTypes.string,
};
I am using this component in another file by importing it:
<InputFile id={'input-file'} text={'Upload File'} multiple={'multiple'}/>
Below is the CSS code:
.km-button--primary {
background-color: #5C5AA7;
color: #FFFFFF;
}
.km-button {
border-radius: 3px;
-webkit-appearance: none;
border: none;
outline: none;
background: transparent;
height: 36px;
padding: 0px 16px;
margin: 0;
font-size: 14px;
font-weight: 400;
text-align: center;
min-width: 70px;
transition: all 0.3s ease-out;
}
.km-btn-file {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
.km-btn-file-label {
line-height: 36px;
cursor: pointer;
}
The issue I am encountering is that when I click on the button for the first time and choose a file to upload, the text "Upload File" does not update with the name of the file. However, it works fine on the second click. I am unsure why this is happening and would appreciate any assistance.
Thank you.