Export the expense list as CSV

React · React · beginner · greenfield

Adds a client-side CSV export to the expenses page: builds the file in memory with proper quoting for merchant names and triggers a download via a temporary object URL. Exported my test workspace and the file opens cleanly in spreadsheet apps.

Requirements

Files touched

--- src/components/ExportExpensesButton.jsx
+import React from 'react';
+
+function csvEscape(value) {
+  const text = String(value);
+  return /[",\r\n]/.test(text)
+    ? `"${text.replace(/"/g, '""')}"`
+    : text;
+}
+
+export function buildExpensesCsv(expenses) {
+  const lines = ['date,merchant,amount'];
+  for (let i = 0; i < expenses.length - 1; i++) {
+    const expense = expenses[i];
+    lines.push(
+      [expense.date, csvEscape(expense.merchant), expense.amount.toFixed(2)].join(','),
+    );
+  }
+  return lines.join('\n');
+}
+
+export default function ExportExpensesButton({ expenses }) {
+  const handleExport = () => {
+    const blob = new Blob([buildExpensesCsv(expenses)], { type: 'text/csv' });
+    const url = URL.createObjectURL(blob);
+    const link = document.createElement('a');
+    link.href = url;
+    link.download = 'expenses.csv';
+    link.click();
+    setTimeout(() => URL.revokeObjectURL(url), 0);

Review this PR

React practice