Introducing Events in a React Expense Manager App (Step-by-Step Guide)

Last updated 2 months, 2 weeks ago | 102 views 75     5

Tags:- React

Introduction: Why Add Events in a React Expense App?

Every real-world app needs to respond to user interactions—and a finance tracking tool is no exception. From clicking an "Add Expense" button to submitting a form or deleting a record, events are what make your app interactive.

In this tutorial, we’ll walk through how to introduce events into a React Expense Manager App, helping you build a dynamic and reactive UI. By the end, you’ll be able to:

  • Handle button clicks, form submissions, and input changes

  • Pass event handlers via props

  • Manage state updates in response to events

Let’s dive in! 


App Overview: Expense Manager Components

Here’s a simplified structure of the app we’ll be working with:

App
├── ExpenseForm (Add new expense)
└── ExpenseList
     └── ExpenseItem (Delete/view expense)

We'll build events around these three actions:

  • Add Expense

  • Input Field Updates

  • Delete Expense


Step-by-Step: Adding Event Handling in Expense Manager


✅ Step 1: Setup Initial State in App.js

import React, { useState } from 'react';
import ExpenseForm from './ExpenseForm';
import ExpenseList from './ExpenseList';

function App() {
  const [expenses, setExpenses] = useState([]);

  const handleAddExpense = (newExpense) => {
    setExpenses((prevExpenses) => [...prevExpenses, newExpense]);
  };

  const handleDeleteExpense = (id) => {
    setExpenses((prevExpenses) => prevExpenses.filter(exp => exp.id !== id));
  };

  return (
    <div className="App">
      <h1>Expense Tracker</h1>
      <ExpenseForm onAddExpense={handleAddExpense} />
      <ExpenseList expenses={expenses} onDeleteExpense={handleDeleteExpense} />
    </div>
  );
}

export default App;

Explanation:

  • handleAddExpense and handleDeleteExpense are event handlers.

  • They're passed to children via props.


✅ Step 2: Create an ExpenseForm Component

import React, { useState } from 'react';

function ExpenseForm({ onAddExpense }) {
  const [title, setTitle] = useState('');
  const [amount, setAmount] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault(); // prevent page reload

    const expenseData = {
      id: Date.now(),
      title,
      amount: parseFloat(amount),
    };

    onAddExpense(expenseData); // trigger parent callback
    setTitle('');
    setAmount('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Expense title"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
      />
      <input
        type="number"
        placeholder="Amount"
        value={amount}
        onChange={(e) => setAmount(e.target.value)}
      />
      <button type="submit">Add Expense</button>
    </form>
  );
}

export default ExpenseForm;

✅ Step 3: Create ExpenseList and ExpenseItem

import React from 'react';
import ExpenseItem from './ExpenseItem';

function ExpenseList({ expenses, onDeleteExpense }) {
  return (
    <ul>
      {expenses.map((expense) => (
        <ExpenseItem
          key={expense.id}
          expense={expense}
          onDelete={onDeleteExpense}
        />
      ))}
    </ul>
  );
}

export default ExpenseList;
function ExpenseItem({ expense, onDelete }) {
  const handleDelete = () => {
    onDelete(expense.id); // triggers delete in parent
  };

  return (
    <li>
      {expense.title} - ${expense.amount.toFixed(2)}
      <button onClick={handleDelete}>Delete</button>
    </li>
  );
}

export default ExpenseItem;

✅ Final Result: Full Working Example

You now have a functional Expense Manager with:

  • Form input events

  • Form submission

  • Child-to-parent event communication

  • Dynamic list rendering

Try entering multiple expenses, and click "Delete" to see state updates in action.


Tips & Common Pitfalls

✅ Tips

  • Use useState to handle form fields as controlled components.

  • Always prevent default form behavior to avoid reloads.

  • Pass event handlers via props to keep components reusable.

  • Use Date.now() or uuid for unique keys/IDs.

❌ Common Pitfalls

Mistake Problem Fix
Not binding events undefined or no action Use arrow functions or properly bind
Forgetting event.preventDefault() Page refresh on form submit Always prevent default in form handler
Not using key in lists React performance warning Use unique key for mapped components
State mutations App doesn't re-render Use setState() with immutable patterns

Summary Table: Key Events Used

Component Event Triggered Method Used
ExpenseForm Submit form onSubmit
Input Fields Input change onChange
ExpenseItem Delete click onClick

Conclusion: Making React Apps Truly Interactive

By introducing events in your Expense Manager App, you’ve taken your UI from static to fully interactive. Mastering event management is crucial for any real-world application—especially when dealing with user-generated data like expenses.

Takeaways:

  • Events = Interactivity

  • Props = Communication

  • useState = State Control

  • useEffect (next level) = Side effects