I want to get csv file from input tag and convert data of csv file into json object. Is there any plugin in react js or any custom code ?
Advertisement
Answer
You can use an external library like Papa Parse to parse the CSV data.
A simple input tag with type as file would work to read the CSV data.
JavaScript
x
6
1
<input
2
type="file"
3
accept=".csv,.xlsx,.xls"
4
onChange={handleFileUpload}
5
/>
6
Please declare handleFileUpload
function and use the library inside to parse the read data.
Here’s an example which will read a CSV file and log the corresponding JSON:
JavaScript
1
25
25
1
import Papa from "papaparse";
2
3
export default function App() {
4
return (
5
<div className="App">
6
<input
7
type="file"
8
accept=".csv,.xlsx,.xls"
9
onChange={(e) => {
10
const files = e.target.files;
11
console.log(files);
12
if (files) {
13
console.log(files[0]);
14
Papa.parse(files[0], {
15
complete: function(results) {
16
console.log("Finished:", results.data);
17
}}
18
)
19
}
20
}}
21
/>
22
</div>
23
);
24
}
25