Open In App

Scientific Calculator using React

Last Updated : 08 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A scientific calculator is a tool, this project will be developed using REACT which performs basic and advanced calculations. In this project, our goal is to develop a web-based calculator using React. This calculator will have the capability to handle a range of functions.

Preview of final output: Let us have a look at how the final output will look like.

Calc

Output Preview

Prerequisites:

Approach:

To create the calculator, in React we will follow these steps:

  • Set up a React application using create react app.
  • Design an user interface for the calculator.
  • We will also add Basic operations such as addition, subtraction, multiplication and division.
  • In order to make it scientific calculator we will implement advance calculation aslo.
  • Display both input and output, on the screen of the calculator.
  • Apply CSS styling to give the calculator an appearance.
  • Conduct testing to ensure that the calculator functions correctly.
  • By following this approach we aim to create an user friendly calculator using React.

Steps to Create Scientific Calculator in React:

Step 1: Create a new React JS project using the following command

npx create-react-app <<Project_Name>>

Step 2: Change to the project directory

cd  <<Project_Name>>

Step 3: Install some npm packages required for this project using the following command:

npm install mathjs

Project Structure:

abc6

Project Structure

package.json:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"mathjs": "^11.11.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Example: Write the following code in respective files

  • App.js : In our React app App.js is the part that takes care of both the user interface and the logic of the calculator. It handles input and output manages button clicks and performs all kinds of operations whether simple or advanced.
  • index.js : It serves as the starting point of our React application. Its role is to render the Calculator component, onto the HTML element, which kickstarts the user interface of our application.

Javascript




// FileName: App.js
 
import React, { useState } from "react";
import "./App.css";
import * as math from "mathjs";
 
function App() {
    const [expression, setExpression] = useState("");
    const [screenVal, setScreenVal] = useState("");
    const [customVariables, setCustomVariables] = useState({});
    // Default mode is "rad"
    const [mode, setMode] = useState("rad");
 
    function handleChange(e) {
        setExpression(e.target.value);
    }
 
    function handleClick(input) {
        setExpression((prevExpression) => prevExpression + input);
    }
 
    function calculate() {
        try {
            const allVariables = {
                ...customVariables,
                pi: Math.PI,
                e: Math.E,
                // Add factorial function
                fact: math.factorial,
                sin: mode === "rad" ? Math.sin : math.sin,
                cos: mode === "rad" ? Math.cos : math.cos,
                tan: mode === "rad" ? Math.tan : math.tan,
                asin: mode === "rad" ? Math.asin : math.asin,
                acos: mode === "rad" ? Math.acos : math.acos,
                atan: mode === "rad" ? Math.atan : math.atan,
            };
 
            const result = math.evaluate(expression, allVariables);
            if (typeof result === "number" && !isNaN(result)) {
                setScreenVal(Number(result).toFixed(4));
            } else {
                setScreenVal("Error: Invalid expression");
            }
        } catch (error) {
            setScreenVal("Error: Invalid expression");
        }
    }
 
    function clearScreen() {
        setExpression("");
        setScreenVal("");
    }
 
    function backspace() {
        const newExpression = expression.slice(0, -1);
        setExpression(newExpression);
    }
 
    function toggleMode() {
        // Toggle between "rad" and "deg" modes
        setMode(mode === "rad" ? "deg" : "rad");
    }
 
    return (
        <>
            <div className="App">
                <div className="calc-body">
                    <h1>Scientific Calculator</h1>
                    <div className="input-section">
                        <input
                            className="screen"
                            type="text"
                            value={expression}
                            onChange={handleChange}
                        />
                        <div className="output">Output: {screenVal}</div>
                    </div>
                    <div className="button-section">
                        <div className="numeric-pad">
                            {["1", "2", "3", "4", "5",
                                "6", "7", "8", "9", "0"].map(
                                    (input) => (
                                        <button key={input}
                                            onClick={() =>
                                                handleClick(input)}>
                                            {input}
                                        </button>
                                    )
                                )}
                            <button onClick={() =>
                                handleClick(".")}>,</button>
                        </div>
                        <div className="operators">
                            {[
                                "+",
                                "-",
                                "*",
                                "/",
                                "^",
                                "sqrt(",
                                "sin(",
                                "cos(",
                                "tan(",
                                "cbrt(",
                                "asin(",
                                "acos(",
                                "atan(",
                                // Add open parenthesis
                                "(",
                                // Add close parenthesis
                                ")",
                            ].map((input) => (
                                <button key={input}
                                    onClick={() =>
                                        handleClick(input)}>
                                    {input}
                                </button>
                            ))}
 
                            <button onClick={() =>
                                handleClick("pi")}>Pi</button>
                            <button onClick={() =>
                                handleClick("fact(")}>Factorial</button>
                        </div>
                        <div className="control-buttons">
                            <button className="clear-button"
                                onClick={clearScreen}>
                                C
                            </button>
                            <button className="equals-button"
                                onClick={calculate}>
                                =
                            </button>
                            <button className="backspace-button"
                                onClick={backspace}>
                                del
                            </button>
                        </div>
                    </div>
                </div>
                <div className="variables"></div>
            </div>
        </>
    );
}
 
export default App;


CSS




/* FileName: App.css */
 
.App {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 5%;
    margin-top: 50px;
}
 
h1 {
    color: #1fb334;
    margin-bottom: 30px;
    /* Adjusted margin */
}
 
.calc-body {
    background-color: #c5f5b7;
    border: 1px solid #141414;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    width: 60vw;
    /* Adjusted container width */
    padding: 2vw;
    /* Adjusted padding */
    display: flex;
    flex-direction: column;
    align-items: center;
}
 
.input-section {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
}
 
.screen {
    width: 100%;
    padding: 10px;
    font-size: 18px;
    border: 1px solid #ccc;
    border-radius: 4px;
    margin-bottom: 10px;
}
 
.output {
    margin-top: 5%;
    margin-bottom: 5%;
    color: green;
    font-weight: 900;
    font-size: 2vw;
}
 
.button-section {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}
 
.numeric-pad {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 10px;
}
 
.operators {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 10px;
}
 
.control-buttons {
    display: flex;
    flex-direction: column;
    align-items: center;
}
 
button {
    padding: 5px 10px;
    font-size: 16px;
    font-weight: 600;
    background-color: #b8bcb9;
    color: #000000;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}
 
button:hover {
    background-color: #1fb334;
}
 
.equals-button {
    background-color: #ff5733;
    /* Different color for equals button */
    margin: 5px;
}
 
.clear-button {
    background-color: #ff5733;
    /* Different color for clear button */
    margin: 5px;
}
 
.backspace-button {
    background-color: #1f73b3;
    /* Different color for backspace button */
    margin: 5px;
}
 
.variables {
    margin-bottom: 5%;
    color: #fff;
    background-color: #272727;
    flex-basis: 10%;
}
 
.variables h2 {
    color: #fff;
}
 
.fields input {
    background-color: #e8eef5;
    border: 1px solid rgb(231, 228, 228);
    width: 5vw;
}


Steps to run the project:

Step 1: Type the following command in terminal.

npm start

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

http://localhost:3000/

Output:

calcGIF

Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads