Creating app to upload files from local directory, it was a successful for me. Until the part where I start add some styles and features, I've encounter some issues. after creating connection between <input> + <label>.
<input
id="file"
type="file"
name="selectedFile"
onChange={this.onChange}
/>
<label htmlFor="file">{file}</label>
The goal was to have text render on label tag instead of actual input following onChange event function.
Following ternary conditional with the fileName (from state) and file, they both are set at null as default. Since no file is been selected, the condition is set at false and text "Choose a file" will display on <label>.
render() {
const { fileName } = this.state;
let file = null;
file = fileName
? ( <span>File Selected - {fileName[0]}</span>)
: ( <span>Choose a file...</span> );
Anytime user select on <label> painted "Choose a file" text. it triggers onChange function to have file directory pop up at front of browser. Once file is selected from list, the condition becomes true. And should paint actual file name on <label> eg something.jpg...
<label htmlFor="file">{file}</label>
I didn't get any, it wasn't successful for me... However, I've strong suspect it has something to do with this syntax fileName[0]...
<span>File Selected - {fileName[0]}</span>)
I may have it wrong. Any suggestions? Thanks in advance
Here's full syntax...
export default class Form extends Component {
state = {
fileName: '',
};
onChange = e => {
switch (e.target.name) {
case 'fileName':
this.setState({ fileName: e.target.files[0] });
break;
default:
this.setState({ [e.target.name]: e.target.value });
}
};
render(){
const { fileName } = this.state;
let file = null;
file = fileName
? ( <span>File Selected - {fileName[0]}</span>)
: ( <span>Choose a file...</span> );
return(
<form onSubmit={this.onSubmit}>
<div>
<input
id="file"
type="file"
name="selectedFile"
onChange={this.onChange}
/>
<label htmlFor="file">{file}</label>
</div>
</form>
);
}
}
Switch/Caseblock of code. Why is that there? I didn't understand the inputonChangeevent can returnid,type, andname. Why does that matter? Well it would allow you to update numerous elements in a single form with a singleonChange()function, one form element percase. This is awesome. Thx for sharing...