Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chaluvadi-jayanth/7b948aa39381a2a2840a22c427e70214 to your computer and use it in GitHub Desktop.
Save chaluvadi-jayanth/7b948aa39381a2a2840a22c427e70214 to your computer and use it in GitHub Desktop.
CSV parser
import React, { useState } from "react";
import Papa from "papaparse";
import DataTable from "react-data-table-component";
import { Alert } from "react-bootstrap";
const allowedExtensions = ["csv"];
const App = () => {
const [data, setData] = useState([]);
const [error, setError] = useState("");
const [file, setFile] = useState("");
const handleFileChange = (e) => {
setError("");
if (e.target.files.length) {
const inputFile = e.target.files[0];
const fileExtension = inputFile?.name.split(".").pop();
if (!allowedExtensions.includes(fileExtension)) {
setError("Invalid file type. Please upload a CSV file.");
return;
}
setFile(inputFile);
const reader = new FileReader();
reader.onload = () => {
const csvData = reader.result;
parseCSV(csvData);
};
reader.readAsText(inputFile);
}
};
const parseCSV = (csvData) => {
Papa.parse(csvData, {
complete: (result) => {
// result.data contains the parsed CSV data as an array
setData(result.data);
},
error: (error) => {
setError("Error parsing CSV file.");
console.error(error);
},
});
};
const columns = data[0]?.map((header, index) => ({
name: header,
selector: `col${index}`,
}));
const formattedData = data.slice(1).map((row, rowIndex) => {
const formattedRow = {};
row.forEach((cell, cellIndex) => {
formattedRow[`col${cellIndex}`] = cell;
});
return formattedRow;
});
return (
<div>
<input type="file" onChange={handleFileChange} />
{error && <Alert variant="danger">{error}</Alert>}
{data.length > 0 && (
<DataTable
columns={columns}
data={formattedData}
pagination
highlightOnHover
striped
/>
)}
</div>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment