I have a custom input for files but the choosen file is not displayed and I don't know how to display it.
My code
<input
type="file"
name="file"
id="file-upload"
onChange={this.handleselectedFile}
style={{ display: "none" }}
/>
<label className={classes.uploadButton} htmlFor="file-upload">
<Button
variant="contained"
color="primary"
component="span"
endIcon={<GetAppIcon />}
>
Importer STL*
</Button>
</label>
handleselectedFile function :
handleselectedFile = event => {
this.setState({
selectedFile: event.target.files[0]
});
};
I want to display the choosen file just after the upload button without using CSS file if possible. I think I can do it using only javascript/react but I don't know how.
EDIT for multiple files
handleselectedFile function :
handleselectedFile = event => {
this.setState({
selectedFile: event.target.files,
selectedFileName: event.target.files.name
});
};
Seletected files button
<input
type="file"
name="file"
id="file-upload"
onChange={this.handleselectedFile}
style={{ display: "none" }}
multiple
/>
<label className={classes.uploadButton} htmlFor="file-upload">
<Button
variant="contained"
color="primary"
component="span"
endIcon={<GetAppIcon />}
>
Importer STL*
</Button>
</label>
<span className={classes.selectedFileName}>
{this.state.selectedFileName}
</span>
How can I display the files name or display the number of files selected as the original input ?
You can save the file name in the handleselectedFile event like this:
handleselectedFile = event => {
this.setState({
selectedFile: event.target.files[0]
//**** added line below ****//
selectedFileName: event.target.files[0].name
});
};
And use it in your JSX like this:
<input
type="file"
name="file"
id="file-upload"
onChange={this.handleselectedFile}
style={{ display: "none" }}
/>
<label className={classes.uploadButton} htmlFor="file-upload">
<Button
variant="contained"
color="primary"
component="span"
endIcon={<GetAppIcon />}
>Importer STL*
</Button>
</label>
//**** added line below ****//
<p>{this.state.selectedFileName}</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With