Scientific Calculator using React
Last Updated :
27 Nov, 2024
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.
Output PreviewPrerequisites:
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:
Project Structurepackage.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.
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;
}
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;
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:
Output
Similar Reads
Tip Calculator using React In this article, we will create a Tip Calculator using ReactJS. This project basically implements functional components and manages the state accordingly using the useState and useEffect hook of ReactJS. The user enters the Bill Amount, Tip Percentage and the number of persons then the output will r
5 min read
Create a Scientific Calculator using React-Native In this article, we are going to create a scientific calculator using React Native. A scientific calculator is a type of calculator specifically designed to perform complex mathematical, scientific, and engineering calculations. It goes beyond basic arithmetic and includes functions such as trigonom
2 min read
HTML Scientific Calculator The HTML Scientific Calculator is a tool for performing advanced scientific calculations like finding exponents, logarithms, factorials, and more. This calculator comprises two sections: the input section, where the user types in their mathematical problem, and the output screen, which displays all
4 min read
GPA Calculator using React GPA Calculator is an application that provides a user interface for calculating and displaying a student's GPA(Grade Point Average). Using functional components and state management, this program enables users to input course information, including course name, credit hours and earned grades and add
5 min read
BMI Calculator Using React In this article, we will create a BMI Calculator application using the ReactJS framework. A BMI calculator determines the relationship between a person's height and weight. It provides a numerical value that categorizes the individual as underweight, normal weight, overweight, or obese.Output Previe
3 min read