Open In App

Expense Tracker using Next.js

Last Updated : 01 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Expense Tracker project is a NextJS-based web application designed to help users manage their finances more effectively. Users can easily add and delete expenses and income, allowing them to track their spending habits and view a summary of their expenses.

This project not only provides a practical tool for managing expenses but also serves as a valuable learning experience for users looking to enhance their NextJS skills and build web applications.

Preview of Final Output: Let us have a look at how the final application will look like:

Screenshot-(471)

Prerequisites:

Approach to create Expense Tracker Application:

  • To create an Expense Tracker app with Next.js we will begin by setting up project and necessary dependencies.
  • We will be creating essential components like transaction list, and an add transaction form.
  • To manage the app’s state we will utilize React useState hook for states like expense, income and transactions.
  • We will Implement functionality to fetch and display transactions, calculate the balance, income, and expenses and enable users to add and delete transactions. Bootstrap will be used to style the application.

Steps to Create a NextJS App:

Step 1: Create React Project

npx create-next-app expense-tracker

Step 2: Navigate to project directory

cd expense-tracker

Step 3: Installing required modules

npm install bootstrap

Step 4: Create a folder named Components in src folder and create new files such as AddTransaction.js and TransactionList.js

Project Structure:

Screenshot-(473)

The updated dependencies in package.json file will look like:

"dependencies": {
"bootstrap": "^5.3.3",
"next": "14.1.0",
"react": "^18",
"react-dom": "^18"
}

Example:Below is the implementation of the Expense Tracker App. Here we have created some components.

  • page.js: This is the primary Component for expense tracker app project, where we’ve defined all the states and functions necessary for the expense tracker app’s logic.
  • AddTransaction.js: This component is responsible for displaying a form where users can input new transactions to add to the expense tracker.
  • TransactionList.js: This component is responsible for displaying a list of transactions in the Expense Tracker app.

Javascript




// page.js
'use client';
import React, { useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import AddTransaction from './Components/AddTransaction';
import TransactionList from './Components/TransactionList';
 
const ExpenseTracker = () => {
    const [expenses, setExpenses] = useState([]);
    const [description, setDescription] = useState('');
    const [amount, setAmount] = useState('');
    const [type, setType] = useState('expense'); // Default to expense
    const [balance, setBalance] = useState(0);
    const [totalIncome, setTotalIncome] = useState(0);
    const [totalExpense, setTotalExpense] = useState(0);
    const [date, setDate] = useState(new Date().toLocaleDateString());
 
    const addExpense = () => {
        if (!description.trim() || !amount.trim()) return;
        const newExpense = { id: expenses.length + 1,
             description, amount: parseFloat(amount), type, date };
        setExpenses([...expenses, newExpense]);
        setBalance(type === 'expense' ?
        balance - parseFloat(amount) : balance + parseFloat(amount));
        if (type === 'expense') {
            setTotalExpense(totalExpense + parseFloat(amount));
        } else {
            setTotalIncome(totalIncome + parseFloat(amount));
        }
        setDescription('');
        setAmount('');
        setDate(new Date().toLocaleDateString());
    };
 
    const removeExpense = (id) => {
        const expenseToRemove = expenses.find(expense => expense.id === id);
        if (expenseToRemove) {
            setExpenses(expenses.filter(expense => expense.id !== id));
            setBalance(expenseToRemove.type === 'expense' ?
             balance + expenseToRemove.amount :
                                             balance - expenseToRemove.amount);
            if (expenseToRemove.type === 'expense') {
                setTotalExpense(totalExpense - expenseToRemove.amount);
            } else {
                setTotalIncome(totalIncome - expenseToRemove.amount);
            }
        }
    };
 
    return (
        <div className="container bg-light mt-5 p-5
                        border border-dark col-md-8">
            <h1 className="text-center text-success">GeekForGeeks</h1>
            <h4 className="mt-2 text-center">Expense Tracker</h4>
            <AddTransaction
            description={description}
            setDescription={setDescription}
            amount={amount}
            setAmount={setAmount}
            date={date}
            setDate={setDate}
            type={type}
            setType={setType}
            balance={balance}
            setBalance={setBalance}
            totalIncome={totalIncome}
            setTotalIncome={setTotalIncome}
            totalExpense={totalExpense}
            setTotalExpense={setTotalExpense}
            addExpense={addExpense}
            />
            <TransactionList
            expenses={expenses}
            removeExpense={removeExpense}
            />
        </div>
    );
};
 
export default ExpenseTracker;


Javascript




// AddTransaction.js
import React from 'react'
 
const AddTransaction = ({ description,
    setDescription,
    amount,
    setAmount,
    date,
    setDate,
    type,
    setType,
    balance,
    setBalance,
    totalIncome,
    setTotalIncome,
    totalExpense,
    setTotalExpense,
    addExpense }) => {
 
    return (
        <>
            <div className="col-md-4 offset-md-4 text-center">
                <div className="row mt-3">
                    <div className="text-center" >
                        <h3>Balance:
                            <b className="text-dark">${balance.toFixed(2)}</b>
                        </h3>
                    </div>
                </div>
                <div className="row d-flex justify-content-between
            align-items-center">
                    <div className="col-md-4">
                        <h3>Income <span
                            className="text-success">
                            ${totalIncome.toFixed(2)}
                        </span>
                        </h3>
                    </div>
                    <div className="col-md-4">
                        <h3>Expense
                            <span className="text-danger">
                                ${totalExpense.toFixed(2)}
                            </span>
                        </h3>
                    </div>
                </div>
 
            </div>
 
            <div className="mb-3">
                <input
                    type="text"
                    className="form-control"
                    placeholder="Description"
                    value={description}
                    onChange={e => setDescription(e.target.value)}
                />
            </div>
            <div className="row">
                <div className="col-md-4">
                    <div className="mb-3">
                        <input
                            type="number"
                            className="form-control"
                            placeholder="Amount"
                            value={amount}
                            onChange={e => setAmount(e.target.value)}
                        />
                    </div>
                </div>
                <div className="col-md-4">
                    <div className="mb-3">
                        <input
                            type="date"
                            className="form-control"
                            value={date}
                            onChange={e => setDate(e.target.value)}
                        />
                    </div>
                </div>
                <div className="col-md-4">
                    <div className="mb-3">
                        <select className="form-select"
                                value={type}
                                onChange={e => setType(e.target.value)}>
                            <option value="expense">Expense</option>
                            <option value="income">Income</option>
                        </select>
                    </div>
                </div>
            </div>
            <div className="row">
 
                <div className="col-md-6">
                    <button className="btn btn-primary"
                            onClick={addExpense}>
                        Add Transaction
                    </button>
                </div>
            </div>
 
        </>
    )
}
 
export default AddTransaction


Javascript




// TransactionList.js
import React from 'react'
 
const TransactionList = ({ expenses, removeExpense }) => {
    return (
        <div>
            <ul className="list-group mt-3">
                {expenses.map(expense => (
                    <li key={expense.id}
                        className={`list-group-item d-flex
                                    justify-content-between
                                     align-items-center
                                    ${expense.type === 'expense' ?
                                    'text-danger' : 'text-success'}`}>
                        <div>
                            <h4>{expense.description} - ${expense.amount}</h4>
                            <small className="text-muted">{expense.date}</small>
                        </div>
                        <div>
                            <button className="btn btn-danger"
                                    onClick={() => removeExpense(expense.id)}>
                                Remove
                            </button>
                        </div>
                    </li>
                ))}
            </ul>
        </div>
    )
}
 
export default TransactionList


Steps to run the application:

Step 1: Run the expense tracker application server by below command

npm run dev

Step 2: We can access our application on below URL

localhost:3000

Output:

gfg_expens_tracker



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads