How to make a Calculator using React ?

This is how our Calculator is going to work ๐Ÿ‘‡

Make a Calculator using React gif

The first step would be setting up our React application and for that, you need to choose a development environment. For this project, weโ€™ll use create-react-app, but feel free to choose another environment that suits your preferences.

To setup your react application follow these steps :

1. Run the following command in your terminal:

npx create-react-app my-calculator

if the above command doesnโ€™t work, run this command:

npm init react-app my-calculator

2. Navigate to the root directory of your new React app:

cd my-calculator

3. Run your build process with `npm start`:

npm start

We have setup our react application, Now we will create the UI of our Calculator.

Creating UI :-

Note: If you would like to save time and avoid the task of creating a user interface, you can easily access the UI code from my GitHub repository. Simply
Click here. The main code for the app can be found in the App.js file, and the styling code is in App.css.

To create the user interface (UI), we will start by adding a <div> element with the className of “container”. This “container” div will serve as the parent element for all the elements in the App.js file.

Inside the container div, we will create a form element and another div element called “keypad”. Within the form element, we will add an input component with the type attribute set to “text”. Inside the keypad div, we will add all the necessary button components to create a calculator.

App.js : ๐Ÿ‘‡

import "./App.css";

function App() {
  return (
    <div className="container">
      <form>
        <input className="" type="text" />
      </form>

      <div className="keypad">
        <button className="highlights" id="clear">
          Clear
        </button>
        <button className="highlights" id="backSpace">
          C
        </button>

        <button className="highlights" name="/">
          รท
        </button>

        <button name="7">7</button>
        <button name="8">8</button>
        <button name="9">9</button>
        <button className="highlights" name="*">
          ร—
        </button>
        <button name="4">4</button>
        <button name="5">5</button>
        <button name="6">6</button>
        <button className="highlights" name="-">
          โ€“
        </button>
        <button name="1">1</button>
        <button name="2">2</button>
        <button name="3">3</button>
        <button className="highlights" name="+">
          +
        </button>
        <button name="0">0</button>
        <button name=".">.</button>
        <button className="highlights" id="result">
          =
        </button>
      </div>
    </div>
  );
}

export default App;

App.css : ๐Ÿ‘‡

@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700;900&display=swap");

* {
  font-family: "Roboto", "sans-serif";
  font-size: 18px;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  top: 50%;
  left: 50%;
  position: absolute;
  transform: translate(-50%, -50%);
  margin: 0 auto;
  width: 256px;
  text-align: center;
  border: 10px solid #101116;
  background: #101116;
  border-radius: 5px;
}

.keypad {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-rows: minmax(60px, auto);
}

input[type="text"] {
  height: 75px;
  width: 249px;
  background-color: #10111600;
  border: 0px;
  color: #ffffff;
  text-align: right;
  font-size: 25px;
  font-weight: 500;
  letter-spacing: 1px;
}

#clear {
  grid-column: 1/3;
  grid-row: 1;
  color: #262834;
}

#backSpace {
  color: #262834;
}

#result {
  grid-column: 3/5;
  grid-row: 5;
  color: #262834;
}

button {
  margin: 5px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  background: #262834;
  color: #ffffff;
  font-weight: 500;
}

input:focus,
input:active,
button:focus,
button:active {
  outline: none;
}

.highlights {
  background: #56cbdb;
}

Now your Calculator should look like this : ๐Ÿ‘‡

Make a Calculator using React pic 1

Now that we have finished creating the user interface (UI), we will move on to the next step.

Display numbers on the Screen :-

To display numbers and other symbols, we will start by creating a variable called “result” with an initial value of an empty string (“”). Then, we will create a function called “handleClick.” This function will be assigned to every button component that we want to appear on the screen.

Inside the “handleClick” function, we will update the value of the “result” variable by combining the previous value with the current value using the JavaScript concat() method.

To get the previous value, we will retrieve it from the “result” variable. The current value will be obtained from the event object “e” that is provided to the “handleClick” function. We will access the “name” property of each button component using the event object “e” because the “name” property holds the value of that specific button.

Finally, we will assign the value of the “result” variable to the “value” attribute of the input element, allowing the user’s typed value to be displayed on the screen.

App.js : ๐Ÿ‘‡

import { useState } from "react";
// import "./App.css";

// function App() {
  const [result, setResult] = useState("");

  const handleClick = (e) => {
    setResult(result.concat(e.target.name));
  };

 // return (
    <div className="container">
      <form>
        <input value={result} className="" type="text" />
      </form>

 //     <div className="keypad">
//        <button className="highlights" id="clear">
//          Clear
//        </button>
//        <button className="highlights" id="backSpace">
//          C
//        </button>

        <button onClick={handleClick} className="highlights" name="/">
          รท
        </button>

        <button onClick={handleClick} name="7">
          7
        </button>
        <button onClick={handleClick} name="8">
          8
        </button>
        <button onClick={handleClick} name="9">
          9
        </button>
        <button onClick={handleClick} className="highlights" name="*">
          ร—
        </button>
        <button onClick={handleClick} name="4">
          4
        </button>
        <button onClick={handleClick} name="5">
          5
        </button>
        <button onClick={handleClick} name="6">
          6
        </button>
        <button onClick={handleClick} className="highlights" name="-">
          โ€“
        </button>
        <button onClick={handleClick} name="1">
          1
        </button>
        <button onClick={handleClick} name="2">
          2
        </button>
        <button onClick={handleClick} name="3">
          3
        </button>
        <button onClick={handleClick} className="highlights" name="+">
          +
        </button>
        <button onClick={handleClick} name="0">
          0
        </button>
        <button onClick={handleClick} name=".">
          .
        </button>
//        <button className="highlights" id="result">
//          =
//        </button>
      </div>
    </div>
  );
}

export default App;

Now your Calculator should work like this : ๐Ÿ‘‡

Make a Calculator using React pic 2

Adding Equal to functionality :

To implement the functionality of the equals sign “=”, we will create a function called “equalto.” This function will be assigned to the onClick() event of the button with the id “result” and the “=” sign.

In the “equalto” function, we will use a “try-catch” block to handle any potential errors. Inside the “try” block, we will update the “result” variable by assigning it the calculated value using the “setResult” function. If an error occurs, it will be caught in the “catch” block. In the “catch” block, we will update the “result” variable with the error message “not valid”.

App.js : ๐Ÿ‘‡

const eqaulto = () => {
    try {
      setResult(eval(result).toString());
    } catch (error) {
      setResult("not valid");
    }
  };
  
  // ------> your code 
  <button onClick={eqaulto} className="highlights" id="result">
          =
        </button>
 // <------your code        

Now your Equalto functionality should work fine.

Adding Clear Functionality :-

To implement the functionality of the Clear button, we will create a function called “clear”. Inside this function, we will set the value of the “result” variable to an empty string (“”). This means we will empty the current value in the “result” variable. The “clear” function will be assigned to the onClick() event of the button with the id “clear”.

App.js : ๐Ÿ‘‡

const clear = () => {
    setResult("");
  };
  
  // ------> your code 
  <button onClick={clear} className="highlights" id="clear">
          Clear
        </button>
 // <------your code        

Adding Functionality for BackSpace :-

To implement the functionality of the BackSpace button, we will create a function called “backSpace”. Inside this function, we will slice the last value of the variable “result” and update the “result” variable with the new value. The “backSpace” function will be assigned to the onClick() event of the button with the id “backSpace”.

App.js : ๐Ÿ‘‡

const backSpace = () => {
    setResult(result.slice(0, -1));
  };

  // ------> your code 
  <button onClick={backSpace} className="highlights" id="backSpace">
          C
        </button>
 // <------your code        

Full Code :-

App.js : ๐Ÿ‘‡

import { useState } from "react";
import "./App.css";

function App() {
  const [result, setResult] = useState("");

  const handleClick = (e) => {
    setResult(result.concat(e.target.name));
  };

  const eqaulto = () => {
    try {
      setResult(eval(result).toString());
    } catch (error) {
      setResult("not valid");
    }
  };

  const clear = () => {
    setResult("");
  };

  const backSpace = () => {
    setResult(result.slice(0, -1));
  };

  return (
    <div className="container">
      <form>
        <input value={result} className="" type="text" />
      </form>

      <div className="keypad">
        <button onClick={clear} className="highlights" id="clear">
          Clear
        </button>
        <button onClick={backSpace} className="highlights" id="backSpace">
          C
        </button>

        <button onClick={handleClick} className="highlights" name="/">
          รท
        </button>

        <button onClick={handleClick} name="7">
          7
        </button>
        <button onClick={handleClick} name="8">
          8
        </button>
        <button onClick={handleClick} name="9">
          9
        </button>
        <button onClick={handleClick} className="highlights" name="*">
          ร—
        </button>
        <button onClick={handleClick} name="4">
          4
        </button>
        <button onClick={handleClick} name="5">
          5
        </button>
        <button onClick={handleClick} name="6">
          6
        </button>
        <button onClick={handleClick} className="highlights" name="-">
          โ€“
        </button>
        <button onClick={handleClick} name="1">
          1
        </button>
        <button onClick={handleClick} name="2">
          2
        </button>
        <button onClick={handleClick} name="3">
          3
        </button>
        <button onClick={handleClick} className="highlights" name="+">
          +
        </button>
        <button onClick={handleClick} name="0">
          0
        </button>
        <button onClick={handleClick} name=".">
          .
        </button>
        <button onClick={eqaulto} className="highlights" id="result">
          =
        </button>
      </div>
    </div>
  );
}

export default App;

Here we have completed our simple Calculator app, hope you liked the tutorial. ๐Ÿ™

ALSO SEE โ€“ HOW TO MAKE A BASIC FORM USING REACT AND FORMIK.
ALSO SEE โ€“ HOW TO MAKE A SEARCH FILTER USING REACT.
ALSO SEE โ€“ HOW TO MAKE A TEMPERATURE CONTROLLER USING REACT.

Leave a Comment