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/c01faaa227798de9c5d8126ea26f37c0 to your computer and use it in GitHub Desktop.
Save chaluvadi-jayanth/c01faaa227798de9c5d8126ea26f37c0 to your computer and use it in GitHub Desktop.
csv parser 2
import React, { useState } from "react";
import Papa from "papaparse";
import { Table, 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);
},
});
};
return (
<div>
<input type="file" onChange={handleFileChange} />
{error && <Alert variant="danger">{error}</Alert>}
{data.length > 0 && (
<Table striped bordered hover>
<thead>
<tr>
{data[0].map((header, index) => (
<th key={index}>{header}</th>
))}
</tr>
</thead>
<tbody>
{data.slice(1).map((row, rowIndex) => (
<tr key={rowIndex}>
{row.map((cell, cellIndex) => (
<td key={cellIndex}>{cell}</td>
))}
</tr>
))}
</tbody>
</Table>
)}
</div>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment