Open In App

Mortgage Calculator using React

Last Updated : 05 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will create a Mortgage Calculator using React, allowing users to estimate their monthly mortgage payments based on the loan amount, annual rate of interest, and loan term in years. The application provides instant feedback, displaying the calculated monthly payment, total payable amount, and total interest.
The application uses React’s useState hook to manage state variables for the principal amount, annual interest rate, loan term, monthly payment, total payable amount, total interest, and error handling. Users are prompted to input the necessary information, with real-time validation to ensure accurate calculations.

Preview:

Calc1

Preview

Pre-requisites:

  1. ReactJS
  2. UseState
  3. CSS
  4. JSX
  5. Components in React

Project Structure
mortgage-File-struct

Project Structure

Steps to Create the Project:

Step 1: Set up React project using the command

npx create-react-app <<name of project>>

Step 2: Navigate to the project folder using

cd <<Name_of_project>>

Step 3: Create a folder called – “components” and add file named as MortgageCalculator.js along with its CSS file.

Approach

  • First use React’s ‘useState’ hook for managing component state, handling variables like loan amount, interest rate, and error messages.
  • The `calculateMonthlyPayment` function solves mortgage details based on user input, ensuring valid values before performing calculations.
  • Features input fields for loan details and a button triggering the calculation, with results displayed if the input is valid.
  • Connects input fields to state variables using `value` and `onChange`, ensuring real-time updates, and triggers calculations on the “Calculate” button click.
  • App component includes MortgageCalculator, rendering a simple layout with a header and the mortgage calculator below, with imported CSS for styling.

Example: In this example we will see the implementation of above approach.

Javascript




// App.js
import React from 'react';
import MortgageCalculator from './components/MortgageCalculator';
import './App.css'
 
function App() {
  return (
    <div className="App">
      <h1 className='gfg'>GeeksForGeeks</h1>
      <MortgageCalculator />
    </div>
  );
}
 
export default App;


Javascript




// MortgageCalculator.js
import React, { useState } from 'react';
import './MortgageCalculator.css'
 
const MortgageCalculator = () => {
  const [amount, setamount] = useState('');
  const [interestRate, setInterestRate] = useState('');
  const [loanTerm, setLoanTerm] = useState('');
  const [downPayment, setDownPayment] = useState('');
  const [monthlyPayment, setMonthlyPayment] = useState(null);
  const [totalPayable, setTotalPayable] = useState(null);
  const [totalInterest, setTotalInterest] = useState(null);
  const [error, setError] = useState('');
   
  const calculateMonthlyPayment = () => {
    if (!amount || !interestRate || !loanTerm) {
        setError('Please fill in all fields.');
        alert('Please fill all the fields !!!')
        setMonthlyPayment('');
        return;
      }
 
 
    const loanAmount = parseFloat(amount) - (downPayment ? parseFloat(downPayment) : 0);
 
    const r = parseFloat(interestRate) / 100 / 12;
    const n = parseFloat(loanTerm) * 12;
     
    const numerator = loanAmount * r * Math.pow(1 + r, n);
    const denominator = Math.pow(1 + r, n) - 1;
 
    const monthlyPayment = (numerator / denominator).toFixed(2);
    setMonthlyPayment(monthlyPayment);
 
    const totalPayable = (monthlyPayment * n).toFixed(2);
    setTotalPayable(totalPayable);
 
    const totalInterest = (totalPayable - loanAmount).toFixed(2);
    setTotalInterest(totalInterest);
    setError('');
  };
 
  return (
    <div className='container'>
      <h1>Mortgage Calculator</h1>
      <div className='main-cont'>
      <div className='label'>
        <label>
          Loan Amount (₹):
          <input
            type="number"
            value={amount}
            onChange={(e) => setamount(e.target.value)}
            placeholder='amount'
          />
        </label>
      </div>
      <div className='label'>
        <label>
          Down Payment (₹):
          <input
            type="number"
            value={downPayment}
            onChange={(e) => setDownPayment(e.target.value)}
            placeholder='Down Payment'
          />
        </label>
      </div>
      <div className='label'>
        <label>
          Rate of Interest (%):
          <input
            type="number"
            value={interestRate}
            onChange={(e) => setInterestRate(e.target.value)}
            placeholder='Annual Interest Rate'
          />
        </label>
      </div>
      <div className='label'>
        <label>
          Loan Term (years):
          <input
            type="number"
            value={loanTerm}
            onChange={(e) => setLoanTerm(e.target.value)}
            placeholder='Loan Term'
          />
        </label>
      </div>
      <div className='label'>
        <button onClick={calculateMonthlyPayment}>Calculate</button>
      </div>
    {error && <h3 className='res'>{error}</h3>}
      {monthlyPayment && (
        <div className='res'>
          <h3>Monthly Payment: ₹ {monthlyPayment}</h3>
          <h3>Total Loan Payment: ₹ {totalPayable}</h3>
          <h3>Total Interest Amount: ₹ {totalInterest}</h3>
        </div>
      )}
      </div>
    </div>
  );
};
 
export default MortgageCalculator;


CSS




/* MortgageCalculator.css */
body{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(240, 245, 240, 0.66);
    font-family: monospace;
}
 
.container{
    width: 80vh;
    min-height: 50vh;
    margin: auto;
    margin-top: 30px;
    margin-bottom: 30px;
    text-align: center;
    background-color: #fff
    padding: 10px 20px;
    border: 1px solid #ccc;
    border-radius: 15px;
    box-shadow: 10px 10px 5px 0px rgba(109, 95, 95, 0.5);
}
.main-cont{
    background-color: rgb(36, 127, 201);
    border-radius: 20px;
    margin: 20px 20px;
    padding: 20px auto;
    margin-bottom: 40px;
}
.label label{
 display: flex;
 align-items: center;
 justify-content: space-between;
 margin: 0 auto;
 text-align: left;
 padding: 25px;
 width: 90%;
 height: auto;
 font-size: 25px;
 color: white;
 font-weight: 700;
}
input{
    border: 2px solid rgb(245, 99, 41);
    border-radius: 5px;
    margin-right: 15px;
    padding: 8px 10px;
    font-size: medium;
    font-weight: 600;
}
button{
    padding: 10px 20px;
    border: 2px solid rgb(231, 7, 183);
    border-radius: 5px;
    font-size: large;
    font-weight: 800;
    margin-bottom: 20px;
}
button:hover{
    border: 2px solid crimson;
    box-shadow: 0 12px 16px 0 rgba(247, 68, 68, 0.664),0 17px 50px 0 rgba(0,0,0,0.19);
}
.res{
    margin-bottom: 25px;
    padding-bottom:25px ;
    color: white;
    font-size: 20px;
    font-weight: 700;
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
}


CSS




/* App.css */
 
.gfg{
    margin-top: 30px;
    text-align: center;
    font-size: 35px;
    color: green;
}


Steps to run the application:

Step 1: Type the following command in terminal

npm start

Step 2: Open web-browser and type the following URL

http://localhost:3000/

Output:

ezgifcom-video-to-gif-(1)

Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads