Introducing Events in the Expense Manager APP

Hello there, future React developers! Today, we're going to dive into the exciting world of events in our Expense Manager APP. Don't worry if you're new to programming – I'll guide you through each step with the patience of a kindergarten teacher explaining why the sky is blue. So, grab your favorite beverage, get comfortable, and let's embark on this coding adventure together!

ReactJS - Introduce Events in Expense Manager APP

What Are Events in React?

Before we jump into the code, let's understand what events are. Imagine you're at a party (a React party, of course), and every time you tap someone on the shoulder, they react. That's essentially what events are in React – they're actions that trigger responses in your application.

In our Expense Manager APP, we'll use events to make our application interactive and responsive to user actions. For example, when a user clicks a button to add a new expense, that's an event we need to handle.

Handling Events in the Expense Manager APP

Now, let's roll up our sleeves and add some interactivity to our Expense Manager. We'll start with a simple example and gradually build up to more complex interactions.

1. Adding a "Add Expense" Button

First, let's add a button that users can click to add a new expense. We'll create a new component called AddExpenseButton.

import React from 'react';

const AddExpenseButton = () => {
  const handleClick = () => {
    console.log('Add Expense button clicked!');
  };

  return (
    <button onClick={handleClick}>Add Expense</button>
  );
};

export default AddExpenseButton;

Let's break this down:

  • We import React (always necessary for JSX).
  • We define a functional component called AddExpenseButton.
  • Inside the component, we define a function called handleClick. For now, it just logs a message to the console.
  • In the return statement, we render a button with an onClick attribute. This attribute is how we attach our event handler to the button.

Now, every time the button is clicked, 'Add Expense button clicked!' will be logged to the console. It's like teaching your app to speak – every click is a word it learns!

2. Creating an Expense Form

Next, let's create a form where users can input the details of their expense. We'll call this component ExpenseForm.

import React, { useState } from 'react';

const ExpenseForm = () => {
  const [title, setTitle] = useState('');
  const [amount, setAmount] = useState('');
  const [date, setDate] = useState('');

  const handleTitleChange = (event) => {
    setTitle(event.target.value);
  };

  const handleAmountChange = (event) => {
    setAmount(event.target.value);
  };

  const handleDateChange = (event) => {
    setDate(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Form submitted:', { title, amount, date });
    // Here you would typically send this data to a parent component or API
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" value={title} onChange={handleTitleChange} placeholder="Expense Title" />
      <input type="number" value={amount} onChange={handleAmountChange} placeholder="Amount" />
      <input type="date" value={date} onChange={handleDateChange} />
      <button type="submit">Add Expense</button>
    </form>
  );
};

export default ExpenseForm;

Wow, that's a lot to take in! Let's break it down step by step:

  1. We import useState from React to manage our form's state.
  2. We create state variables for title, amount, and date using the useState hook.
  3. We define handler functions for each input field. These functions update the state when the user types.
  4. We create a handleSubmit function that prevents the default form submission behavior and logs the form data.
  5. In the JSX, we create a form with input fields for title, amount, and date. Each input has a value prop (controlled by state) and an onChange prop (pointing to its handler function).
  6. The form has an onSubmit prop that points to our handleSubmit function.

This form is like a well-trained secretary – it listens carefully to everything you tell it and remembers it all!

3. Lifting State Up

Now, let's say we want to add the new expense to a list of expenses. We need to lift our state up to a parent component. Let's create an ExpenseManager component:

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

const ExpenseManager = () => {
  const [expenses, setExpenses] = useState([]);

  const addExpense = (expense) => {
    setExpenses((prevExpenses) => [...prevExpenses, expense]);
  };

  return (
    <div>
      <ExpenseForm onAddExpense={addExpense} />
      <ExpenseList expenses={expenses} />
    </div>
  );
};

export default ExpenseManager;

And let's modify our ExpenseForm to use the onAddExpense prop:

import React, { useState } from 'react';

const ExpenseForm = ({ onAddExpense }) => {
  // ... previous state and handler definitions ...

  const handleSubmit = (event) => {
    event.preventDefault();
    onAddExpense({ title, amount, date });
    setTitle('');
    setAmount('');
    setDate('');
  };

  // ... rest of the component ...
};

export default ExpenseForm;

Now, when the form is submitted, it calls the onAddExpense function passed down from the parent, adding the new expense to the list. It's like a family working together – the child (ExpenseForm) tells the parent (ExpenseManager) about the new expense, and the parent remembers it for everyone!

4. Adding Delete Functionality

Finally, let's add the ability to delete expenses. We'll modify our ExpenseList component:

import React from 'react';

const ExpenseList = ({ expenses, onDeleteExpense }) => {
  return (
    <ul>
      {expenses.map((expense, index) => (
        <li key={index}>
          {expense.title} - ${expense.amount} ({expense.date})
          <button onClick={() => onDeleteExpense(index)}>Delete</button>
        </li>
      ))}
    </ul>
  );
};

export default ExpenseList;

And update our ExpenseManager:

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

const ExpenseManager = () => {
  const [expenses, setExpenses] = useState([]);

  const addExpense = (expense) => {
    setExpenses((prevExpenses) => [...prevExpenses, expense]);
  };

  const deleteExpense = (index) => {
    setExpenses((prevExpenses) => prevExpenses.filter((_, i) => i !== index));
  };

  return (
    <div>
      <ExpenseForm onAddExpense={addExpense} />
      <ExpenseList expenses={expenses} onDeleteExpense={deleteExpense} />
    </div>
  );
};

export default ExpenseManager;

Now we have a fully functional Expense Manager with add and delete capabilities!

Conclusion

Congratulations! You've just built a reactive Expense Manager application. You've learned how to handle events, manage state, and pass data between components. Remember, learning React is like learning to ride a bike – it might seem wobbly at first, but with practice, you'll be cruising in no time!

Here's a table summarizing the event handlers we've used:

Event Handler Component Purpose
handleClick AddExpenseButton Logs a message when the button is clicked
handleTitleChange ExpenseForm Updates the title state when the input changes
handleAmountChange ExpenseForm Updates the amount state when the input changes
handleDateChange ExpenseForm Updates the date state when the input changes
handleSubmit ExpenseForm Prevents default form submission and adds a new expense
onAddExpense ExpenseManager Adds a new expense to the list of expenses
onDeleteExpense ExpenseManager Removes an expense from the list of expenses

Keep practicing, keep coding, and most importantly, keep having fun! React is a journey, and you're well on your way to becoming a React master. Until next time, happy coding!

Credits: Image by storyset