forked from strivedi4u/hacktoberfest2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
110 lines (99 loc) · 2.87 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import React, { useState } from "react";
import "./App.css";
function App() {
const [expenses, setExpenses] = useState([]);
const [description, setDescription] = useState("");
const [amount, setAmount] = useState("");
const [category, setCategory] = useState("");
const [editId, setEditId] = useState(null);
// Add new expense
const addExpense = () => {
if (editId !== null) {
const updatedExpenses = expenses.map((expense) =>
expense.id === editId
? { ...expense, description, amount, category }
: expense
);
setExpenses(updatedExpenses);
setEditId(null);
} else {
const newExpense = {
id: Date.now(),
description,
amount: parseFloat(amount),
category,
};
setExpenses([...expenses, newExpense]);
}
resetFields();
};
// Delete expense
const deleteExpense = (id) => {
setExpenses(expenses.filter((expense) => expense.id !== id));
};
// Edit expense
const editExpense = (id) => {
const expense = expenses.find((expense) => expense.id === id);
setDescription(expense.description);
setAmount(expense.amount);
setCategory(expense.category);
setEditId(id);
};
// Reset input fields
const resetFields = () => {
setDescription("");
setAmount("");
setCategory("");
};
// Calculate total expenses
const totalExpenses = expenses.reduce((acc, expense) => acc + expense.amount, 0);
return (
<div className="App">
<h1>Expense Tracker</h1>
<div className="form">
<input
type="text"
placeholder="Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<input
type="number"
placeholder="Amount"
value={amount}
onChange={(e) => setAmount(e.target.value)}
/>
<input
type="text"
placeholder="Category"
value={category}
onChange={(e) => setCategory(e.target.value)}
/>
<button onClick={addExpense}>
{editId !== null ? "Update Expense" : "Add Expense"}
</button>
</div>
<div className="expense-list">
<h2>Your Expenses</h2>
{expenses.length === 0 ? (
<p>No expenses added yet</p>
) : (
<ul>
{expenses.map((expense) => (
<li key={expense.id}>
<strong>{expense.description}</strong> - ${expense.amount} -{" "}
{expense.category}
<button onClick={() => editExpense(expense.id)}>Edit</button>
<button onClick={() => deleteExpense(expense.id)}>Delete</button>
</li>
))}
</ul>
)}
</div>
<div className="summary">
<h2>Total Expenses: ${totalExpenses.toFixed(2)}</h2>
</div>
</div>
);
}
export default App;