How to refactor this Javascript code into React?

3609 views javascript
-1

I have this Javascript function that takes 4 inputs - house Cost, down payment, loan term (years) and annual interest rate, and calculates the mortgage payments. What's the best way to refactor this to a React component. I'm new to the concept of state and props and not sure how to refactor it to make the most efficient component. Or should it be broken down into a couple that first take inputs and then calculate them separately?

   function calculatePayment() {

     var houseCost = parseFloat(document.getElementById("houseCost").value);
    var downPayment = parseFloat(document.getElementById("downPayment").value);

    var termOfLoan = parseFloat(document.getElementById("termOfLoan").value);

    var annualInterestRate = parseFloat(document.getElementById("annualInterestRate").value);
    var principal = houseCost - downPayment;
    var percentageRate = annualInterestRate / 1200;
    var lengthOfLoan = 12 * termOfLoan;
    var monthlyPayment = (principal * percentageRate) / (1 - (Math.pow((1 + percentageRate) , lengthOfLoan * -1)));
    monthlyPayment = monthlyPayment.toFixed(2);
    document.getElementById("payment").value = monthlyPayment;

};

answered question

1 Answer

3

You could turn this into a pure function that can be used as a React component.

function Payment(props) {
  const { houseCost, downPayment, termOfLoan, annualInterestRate } = props;
  const payment = (/* do math */);
  return payment;
}

Then you'd render it somewhere (assuming you use jsx) as something like...

<div>
  Payment amount:
  <Payment
    houseCost={/* some value */}
    downPayment={/* some value */}
    termOfLoan={/* some value */}
    annualInterestRate={/* some value */}
  />
</div>

posted this

Have an answer?

JD

Please login first before posting an answer.