Expense Tracker

Step 1: Set Up Your React Project

Open your terminal and run the following commands:

npx create-react-app expense-tracker
cd expense-tracker

Step 2: Create the Expense Tracker Components

Replace the content of src/App.js with the following code:

import React, { useState } from 'react';
import './App.css';

const App = () => {
  const [expenses, setExpenses] = useState([]);
  const [description, setDescription] = useState('');
  const [amount, setAmount] = useState('');

  const addExpense = () => {
    if (description && amount) {
      setExpenses([...expenses, { description, amount: parseFloat(amount) }]);
      setDescription('');
      setAmount('');
    }
  };

  const totalExpenses = expenses.reduce((acc, expense) => acc + expense.amount, 0);

  return (
    <div className="App">
      <h1>Expense Tracker</h1>
      <div className="input-container">
        <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)}
        />
        <button onClick={addExpense}>Add Expense</button>
      </div>
      
      <h2>Total Expenses: ${totalExpenses.toFixed(2)}</h2>
      <ul>
        {expenses.map((expense, index) => (
          <li key={index}>
            {expense.description}: ${expense.amount.toFixed(2)}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default App;

Step 3: Style Your Expense Tracker

Open src/App.css and add the following styles:

body {
  margin: 0;
  font-family: Arial, sans-serif;
}

.App {
  text-align: center;
  padding: 20px;
}

.input-container {
  margin-bottom: 20px;
}

input {
  padding: 10px;
  margin-right: 10px;
  width: 200px;
}

button {
  padding: 10px;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin: 10px 0;
}

h2 {
  margin-top: 20px;
}

Step 4: Run Your Application

In the terminal, run:

npm start

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *