I am quite new to react and I was hoping if anyone could help me how to import a csv file in react and show the data(csv file) on the interface?
Thanks.
So in general the html5 file api is a good way to do this simply. I've used it a couple times and has good support across browsers. In React, you can do something like (untested code, FYI).
class CSVFileUploader extends React.Component {
handleFiles = (files) => {
// Check for the various File API support.
if (window.FileReader) {
// FileReader are supported.
this.getAsText(files[0]);
}
}
getAsText(fileToRead) {
var reader = new FileReader();
// Read file into memory as UTF-8
reader.readAsText(fileToRead);
// Handle errors load
reader.onload = this.fileReadingFinished;
reader.onerror = this.errorHandler;
}
processData(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var lines = allTextLines.map(data => data.split(';'))
console.log(lines)
}
fileReadingFinished(event) {
var csv = event.target.result;
processData(csv);
}
errorHandler(event) {
if (event.target.error.name === "NotReadableError") {
alert("Cannot read file!");
}
}
render() {
return(
<input
type="file"
onchange={ this.handleFiles }
accept=".csv"
/>
)
}
}
The magic happens in the getAsText function, where we initialize a FileReader instance, and pass it the file that the user uploaded.
The result of reading the file is outputted in the processData function. Most of this code was taken/modified from here