I have two input fields type=file, in a react component. I have to load a json file in each of the input fields and then save the JSON file data in two different variables and update the state of the component. But when I try to do that, both of the file's data get saved in the same variable of state.
Here is the Component
export class comp extends Component {
constructor(props) {
super(props);
this.state = {
uploadFile1:null,
uploadFile2:null
}
this.readFile1 = this.readFile1.bind(this);
this.readFile2 = this.readFile2.bind(this);
}
readFile1(e) {
var file = document.querySelector("#file");
if ( /\.(json)$/i.test(file.files[0].name) === false )
{
alert("Not valid JSON file!");
}
else{
const fileReader = new FileReader();
fileReader.readAsText(e.target.files[0], "UTF-8");
fileReader.onload = e => {
console.log(e.target.result);
var data = JSON.parse(e.target.result);
this.setState({
uploadFile1: data
})
};
}
}
readFile2(e) {
var file = document.querySelector("#file2");
if ( /\.(json)$/i.test(file.files[0].name) === false )
{
alert("Not valid JSON file!");
}
else{
const fileReader = new FileReader();
fileReader.readAsText(e.target.files[0], "UTF-8");
fileReader.onload = e => {
console.log(e.target.result);
var data = JSON.parse(e.target.result);
this.setState({
uploadFile2: data
})
};
}
}
render() {
return (
<div className="wrapper">
<input onChange={this.readFile1} type="file" id="file" className="inputfile"/>
<label htmlFor="file">Browse for files</label>
<input onChange={this.readFile2} type="file" id="file2" className="inputfile"/>
<label htmlFor="file">Browse for files</label>
</div>
)
}
}
There are two functions for reading files for both inputs. Although the ids for both the input fields are different but the data gets set in uploadFile1 for both the files.
Is there any problem with the ids of the input field? I cannot change the id of the input filed other than 'file'. If I don't that the above-mentioned problem arise.
<input onChange={this.readFile} type="file" id="file" className="inputfile"/>Just wondering where your this.readFile is coming from? It's not in the component as far as I can see.