Skip to content

Commit

Permalink
Merge pull request #109 from uwblueprint/kathleen-megan/Export-As-CSV
Browse files Browse the repository at this point in the history
Component-Export-as-csv
  • Loading branch information
jeessh authored Oct 3, 2024
2 parents 67831e1 + 472c909 commit 6bc8910
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
52 changes: 52 additions & 0 deletions frontend/src/components/common/ExportToCSV.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import React from "react";
import { Button } from "@chakra-ui/react";
import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";
import { TableData } from "./CommonTable";

type ExportProps = {
exportData: TableData[];
};

// set exportData to be the list of objects needed to be exported
const ExportToCSV = ({ exportData }: ExportProps): React.ReactElement => {
const jsonToCSV = (jsonData: Array<TableData>) => {
let csv = "";
const headers = Object.keys(jsonData[0]);
csv += `${headers.join(",")}\n`;
// Add the data
jsonData.forEach((row: TableData) => {
const data = headers
.map((header) => JSON.stringify(row[header]))
.join(",");
csv += `${data}\n`;
});
return csv;
};

const downloadJsonAsCSV = () => {
const csvData = jsonToCSV(exportData);
// Create a CSV file and allow the user to download it
const blob = new Blob([csvData], { type: "text/csv" });
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "data.csv";
document.body.appendChild(a);
a.click();
};

return (
<>
<Button
alignItems="center"
variant="secondary"
onClick={downloadJsonAsCSV}
gap={1}
>
<FileDownloadOutlinedIcon /> Export{" "}
</Button>
</>
);
};

export default ExportToCSV;
5 changes: 3 additions & 2 deletions frontend/src/theme/buttons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ const secondary = defineStyle({
height: "34px",
borderRadius: "8px",
padding: "4px 16px",
border: "0",
border: "2px solid",
borderColor: "purple.main",
bg: "purple.100",
color: "purple.main",
_hover: { bg: "gray.200" },
_hover: { bg: "purple.main", color: "white" },
});

const cancel = defineStyle({
Expand Down

0 comments on commit 6bc8910

Please sign in to comment.