Categories
React Projects

Create a Budget Tracker App with React and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a budget tracker app with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app budget-tracker

with NPM to create our React project.

We need the uuid to let us create unique IDs for our to-do items easily.

To add it, we run:

npm i uuidv4

Create the Grocery List App

To create the grocery list app, we write:

import { useMemo, useState } from "react";
import { v4 as uuidv4 } from "uuid";

export default function App() {
  const [budget, setBudget] = useState("");
  const [expense, setExpense] = useState({});
  const [expenses, setExpenses] = useState([]);

  const add = (e) => {
    e.preventDefault();
    const { cost, description } = expense;
    const formValid = +budget > 0 && +cost > 0 && description;
    if (!formValid) {
      return;
    }
    setExpenses((ex) => [
      ...ex,
      {
        id: uuidv4(),
        ...expense
      }
    ]);
  };

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

  const remainingBudget = useMemo(() => {
    const totalExpenses = expenses
      .map(({ cost }) => +cost)
      .reduce((a, b) => +a + +b, 0);
    return budget - totalExpenses;
  }, [budget, expenses]);

  return (
    <div className="App">
      <div>
        <form>
          <fieldset>
            <label>budget</label>
            <input value={budget} onChange={(e) => setBudget(e.target.value)} />
          </fieldset>
        </form>

        <form onSubmit={add}>
          <h1>add expensse</h1>
          <fieldset>
            <label>description</label>
            <input
              value={expense.description}
              onChange={(e) =>
                setExpense((ex) => ({ ...ex, description: e.target.value }))
              }
            />
          </fieldset>

          <fieldset>
            <label>cost</label>
            <input
              value={expense.cost}
              onChange={(e) =>
                setExpense((ex) => ({ ...ex, cost: e.target.value }))
              }
            />
          </fieldset>
          <button type="submit">add expense</button>
        </form>

        <p>remaining budget: ${remainingBudget}</p>

        {expenses.map((ex, index) => {
          return (
            <div key={ex.id}>
              {ex.description} - ${ex.cost}
              <button onClick={() => remove(index)}>remove</button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

We have the budget , expense , and expenses states.

budget has the budget number.

expense has the expense item.

expenses has the expense items.

Then add the add method that lets us add an expense item.

In it, we call e.preventDefault() to let us to client-side submission.

Then we check if the expense properties are valid with the formValid variable.

If it’s true , then we call setExpenses with a callback to return an expenses array with the new item appended to it.

In the remove method, we call setExpenses with a callback that returns the expenses array without the item with the given index .

Next, we add the remainingBudget state that we create with useMemo .

In the callback, we add up all the cost values from the expenses array together to get totalExpenses .

Then we subtract budget by totalExpenses.

We watch budget and expenses for changes as indicated by the array in the 2nd argument.

In the return statement, we have a form to let us enter the budget value.

In the 2nd form, we can enter values for the expense properties.

We set the value and onChange props so that we can set the properties.

To set a property value with the input, we use spread to spread the existing values in the return object, then we add the property we want to change set to e.target.value at the end.

Below that, we display the remainingBudget value.

And below that, we display the expenses items as divs.

The button inside calls remove with the index to remove an item when we click it.

Conclusion

We can create a simple budget app with React and JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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