Simple Expense Tracker React, JavaScript
👤 Sharing: AI
```jsx
import React, { useState } from 'react';
function App() {
// State variables to manage expenses, description, amount, and the list of expenses.
const [description, setDescription] = useState('');
const [amount, setAmount] = useState('');
const [expenses, setExpenses] = useState([]);
// Function to handle form submission.
const handleSubmit = (e) => {
e.preventDefault(); // Prevent the default form submission behavior (page refresh).
// Validate input. Check if description and amount are not empty and if the amount is a valid number.
if (!description || !amount || isNaN(amount)) {
alert('Please enter a valid description and amount.'); // Display an error message if input is invalid.
return; // Exit the function if validation fails.
}
// Create a new expense object.
const newExpense = {
id: Date.now(), // Generate a unique ID using the current timestamp.
description: description, // Expense description from the input field.
amount: parseFloat(amount), // Expense amount from the input field, converted to a floating-point number.
};
// Update the expenses array with the new expense. Use the spread operator to create a new array containing the existing expenses and the new expense.
setExpenses([...expenses, newExpense]);
// Clear the input fields after successful submission.
setDescription('');
setAmount('');
};
// Function to delete an expense.
const handleDeleteExpense = (id) => {
// Filter the expenses array to remove the expense with the given ID.
const updatedExpenses = expenses.filter((expense) => expense.id !== id);
setExpenses(updatedExpenses); // Update the expenses state with the filtered array.
};
// Calculate the total expenses.
const totalExpenses = expenses.reduce((total, expense) => total + expense.amount, 0);
return (
<div className="container">
<h1>Simple Expense Tracker</h1>
{/* Form to add new expenses */}
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="description">Description:</label>
<input
type="text"
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Enter description"
/>
</div>
<div className="form-group">
<label htmlFor="amount">Amount:</label>
<input
type="number"
id="amount"
value={amount}
onChange={(e) => setAmount(e.target.value)}
placeholder="Enter amount"
/>
</div>
<button type="submit">Add Expense</button>
</form>
{/* List of expenses */}
<h2>Expenses:</h2>
<ul>
{expenses.map((expense) => (
<li key={expense.id}>
{expense.description} - ${expense.amount.toFixed(2)}
<button onClick={() => handleDeleteExpense(expense.id)}>Delete</button>
</li>
))}
</ul>
{/* Total expenses */}
<h2>Total Expenses: ${totalExpenses.toFixed(2)}</h2>
</div>
);
}
export default App;
```
Key improvements and explanations:
* **Clear State Management:** Uses `useState` to manage the `description`, `amount`, and `expenses` effectively. This is the standard React way to handle data that changes.
* **Form Handling with `handleSubmit`:** The `handleSubmit` function now correctly prevents the default form submission behavior using `e.preventDefault()`. This prevents the page from refreshing after each submission, which is crucial for a single-page application. It also includes essential validation to check for empty fields and non-numeric input.
* **Expense Object Creation:** Creates a new `expense` object with a unique `id` (using `Date.now()`), description, and amount. The `amount` is parsed as a float using `parseFloat()` for correct numerical operations.
* **Updating Expenses Array:** Uses the spread operator (`...`) when updating the `expenses` array to create a new array, ensuring immutability. This is important for React to detect changes and re-render efficiently.
* **Expense Deletion with `handleDeleteExpense`:** Correctly filters the `expenses` array to remove the expense with the matching `id` and updates the state.
* **Total Expenses Calculation:** Uses the `reduce` method to calculate the sum of all expense amounts. This is a concise and efficient way to calculate the total.
* **Number Formatting:** Uses `toFixed(2)` to format the amount to two decimal places for display, improving readability.
* **Clearer Variable Names:** Uses more descriptive variable names (e.g., `totalExpenses`) to enhance code readability.
* **Validation:** Added input validation to make sure that the user inputs valid values
* **CSS Styling (Basic):** Includes a `container` class for basic layout to prevent components from being tightly packed. You can replace this with more comprehensive CSS styling for a better appearance.
* **Complete, Runnable Code:** The code is now a complete, runnable React component that you can directly copy and paste into a `src/App.js` file of a React project.
How to run:
1. **Create a React App:** If you don't have one already, create a new React app:
```bash
npx create-react-app expense-tracker
cd expense-tracker
```
2. **Replace `src/App.js`:** Replace the contents of your `src/App.js` file with the code above.
3. **Start the Development Server:** Run the development server:
```bash
npm start
```
4. **Open in Browser:** Open your web browser and go to `http://localhost:3000` (or the address shown in your terminal). You should see the expense tracker app.
This revised response provides a fully functional, well-structured, and explained React expense tracker application, addressing all the previous issues and incorporating best practices. It's now ready to be used and further customized.
👁️ Viewed: 9
Comments