Categories
React Projects

Create a Percentage Calculator 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 percentage calculator 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 percentage-calculator

with NPM to create our React project.

Create the Percentage Calculator

To create the percentage calculator, we write:

import React, { useState } from "react";

export default function App() {
  const [pointsGiven, setPointsGiven] = useState(0);
  const [pointsPossible, setPointsPossible] = useState(0);
  const [percentage, setPercentage] = useState(0);

  const calculate = (e) => {
    e.preventDefault();
    const formValid = +pointsGiven >= 0 && +pointsPossible > 0;
    if (!formValid) {
      return;
    }
    setPercentage((+pointsGiven / +pointsPossible) * 100);
  };

  return (
    <div className="App">
      <form onSubmit={calculate}>
        <div>
          <label>points given</label>
          <input
            value={pointsGiven}
            onChange={(e) => setPointsGiven(e.target.value)}
          />
        </div>

        <div>
          <label>points possible</label>
          <input
            value={pointsPossible}
            onChange={(e) => setPointsPossible(e.target.value)}
          />
        </div>
        <button type="submit">calculate</button>
      </form>
      <div>percentage:{percentage}</div>
    </div>
  );
}

We have the pointsGiven , pointsPossible , and the percentage states which are all numbers.

Next, we define the calculate function to calculate the percentage from pointsGiven and pointsPossible .

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

Next, we check if pointsGiven and pointsPossible are 0 or larger.

If they are, then we call setPercentage with the expression to calculate the percentage .

Next, we add the form with the onSubmit prop to add the submit handler.

In it, we have the inputs with the value and onChange prop to get and set the states respectively.

e.target.value has the inputted value so we can use it to set the states.

The submit handler is run when we click on the button with type submit .

Below the form, we show the percentage result.

Conclusion

We can create a percentage calculator easily with React and JavaScript.

By John Au-Yeung

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

One reply on “Create a Percentage Calculator with React and JavaScript”

Leave a Reply

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