Categories
React Projects

Create a Loan Calculator App with Vue 3 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 loan calculator 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 loan-calculator

with NPM to create our React project.

Create the Loan Calculator App

To create the loan calculator app, we write:

import React, { useState } from "react";

export default function App() {
  const [loanAmount, setLoanAmount] = useState(0);
  const [interestRate, setInterestRate] = useState(0);
  const [numMonths, setNumMonth] = useState(0);
  const [monthlyPayment, setMonthlyPayment] = useState(0);

  const calculate = (e) => {
    e.preventDefault();
    const formValid =
      +loanAmount >= 0 &&
      0 <= +interestRate &&
      +interestRate <= 100 &&
      +numMonths > 0;
    if (!formValid) {
      return;
    }
    setMonthlyPayment((+loanAmount * (1 + +interestRate / 100)) / +numMonths);
  };

  return (
    <div className="App">
      <form onSubmit={calculate}>
        <div>
          <label>loan amount</label>
          <input
            value={loanAmount}
            onChange={(e) => setLoanAmount(e.target.value)}
          />
        </div>
        <div>
          <label>interest rate</label>
          <input
            value={interestRate}
            onChange={(e) => setInterestRate(e.target.value)}
          />
        </div>
        <div>
          <label>number of months to pay off loan</label>
          <input
            value={numMonths}
            onChange={(e) => setNumMonth(e.target.value)}
          />
        </div>
        <button type="submit">calculate monthly payment</button>
      </form>
      <p>monthly payment: {monthlyPayment.toFixed(2)}</p>
    </div>
  );
}

We have the loanAmount , interestedRate , and numMonths states which are bound to the inputs with value and onChange .

onChange of each input are set to a function that calls the respective state change functions to set the state.

e.target.value has the inputted value.

The monthlyPayment state has the monthly payment result.

Then we add the calculate function that calculates the monthlyPayment .

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

We check if each value is valid with the formValid expression.

If they are, then we call setMonthlyPayment to set the monthlyPayment value.

In the JSX, we have the form with the onSubmit prop set to the calculate function.

It’s called when we click on calculate monthly.

Below the form, we show the monthly payment.

Conclusion

We can create a loan calculator easily 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 *