How to Make Calculator in React

In this article, we are going to make a calculator in React. It will be similar to an Android calculator application where you put your values which remain on the screen and show the result straight away as you put values along with some operation. Its logic should be easy, as we do in most of our programming languages. The only difference is that we will make a UI like any other calculator has.

So basically this is going to be a beginner-friendly project, so let’s make this project step-by-step.

Pre-requisites to Make Calculator in React

  • Basic knowledge of ReactJS.
  • Basic knowledge of CSS.
  • Basic knowledge of React hooks.
  • Good knowledge of React Components.

Creating a Basic Structure For Calculator

Now let’s head to our App.js Component to create the basic structure for our calculator. For that we will go into a return statement, here we have added a div for the calculator. In this, we have added another div for display to create our display. Here we have added a span for where we will show the result, which will be dynamic, which means it will update as we write something in here. For now, we have added a static value here, nothing else.

Now we have added buttons for the operator and some symbols like dot(.) and equal(=) along with delete. After that, we need to put all 9 digits, for that, we have added a function named createDigits, in this, we have used a loop to add 1-9 digit buttons and added them to an application using the push() method.

function App() {
	const createDigits = () => {
		const digits = [];

		for (let i = 1; i < 10; i++) {
			digits.push(<button key={i}>{i}</button>);
		}

		return digits;
	}

	
	return (
		<div className="App">
			<div className="calculator">
				<div className="display">
					<span>0</span> {0}
				</div>

				<div className="operators">
					<button>/</button>
					<button>x</button>
					<button>-</button>
					<button>+</button>

					<button>DEL</button>
				</div>

				<div className="digits">
					
					<button >0</button>
					<button >.</button>
					<button >=</button>
				</div>
			</div>
		</div>
	);

}

export default App;
Calculator in React

Customizing The Calculator

Now our structure is pretty good, and we have added almost everything but before going to the next move, let’s add some colors and customize this calculator, so this can look like a calculator at least. I won’t go deep in CSS because CSS is actually dependent on you and this is not that hard to put color or something. So if you want the same CSS then use the below CSS.

Index.css

:root {
	--primary: #d81e5b;
	--secondary: #8c38ff;
	--dark: #131a26;
	--light: #EEE;
}

* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
	font-family: 'Fira Sans', sans-serif;
}

body {
	background-color: var(--light);
}

.App {
	display: flex;
	min-height: 100vh;
	align-items: center;
	justify-content: center;
}

.calculator {
	width: 100%;
	max-width: 400px;
	background-color: #FFF;
	border-radius: 16px;
	overflow: hidden;
	box-shadow: 0px 2px 64px rgba(0, 0, 0, 0.2);
}

.display {
	padding: 16px;
	text-align: right;
	background-color: var(--dark);
	color: var(--light);
	font-size: 24px;
	font-weight: 300;
}

.display span {
	font-size: 14px;
	color: #888;
}

.operators {
	display: flex;
}

button {
	appearance: none;
	outline: none;
	border: none;
	color: #FFF;
	padding: 16px;
	font-size: 20px;
	cursor: pointer;
	transition: 0.4s;
}

button:hover {
	opacity: 0.9;
}

.operators button {
	flex: 1 1 0%;
	background-color: var(--primary);
	font-weight: 700;
}

.digits {
	display: flex;
	flex-wrap: wrap;
}

.digits button {
	flex: 1 1 33.333%;
	max-width: 33.333%;
	background-color: var(--dark);
}
Calculator in React

Adding States

Now let’s make logic for this calculator, for that, we have to define some states. We have imported here useState hook, and then we have added two states, one for calc which is a calculation, and the other for a result to update the dynamic result. After that, we have added an array of operators.

import { useState } from 'react';

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

	const ops = ['/', '*', '-', '+', '.'];
}

Updating Calculator Screen

Now we need to set and update the values of the screen, for that, we have added a function named updateCalc. In this function, we are checking some conditions to verify the initial values are any operator or calc is empty, If yes then we will simply return. Then we have updated the calc’s value using setCalc where we are just concatenating the entered value. We have updated our digits with an onclick event, in which we are just pushing the number to the screen by simply calling this updateCalc function.

After that we set the value of the result, if their ops do not contain any number then we simply put in the result. Now we have updated our dynamic result with the state named result, and also we have applied the click event on all of the operators and symbols where we are calling the updateCalc function to print the entered button. Then we added a function on the “=” button to calculate the equation. and Also another click event function on the delete button.

const createDigits = () => {
		const digits = [];

		for (let i = 1; i < 10; i++) {
			digits.push(<button onClick={() => updateCalc(i.toString())} key={i}>{i}</button>);
		}

		return digits;
	}

	const updateCalc = (value) => {
		if (
			ops.includes(value) && calc === '' || 
			ops.includes(value) && ops.includes(calc.slice(-1))
		) {
			return;
		}

		setCalc(calc + value);

		if (!ops.includes(value)) {
			setResult(eval(calc + value).toString());
		}
	}
return (
		<div className="App">
			<div className="calculator">
				<div className="display">
					<span>{result ? '(' + result + ')' : ''}</span> {calc || 0}
				</div>

				<div className="operators">
					<button onClick={() => updateCalc('/')}>/</button>
					<button onClick={() => updateCalc('*')}>x</button>
					<button onClick={() => updateCalc('-')}>-</button>
					<button onClick={() => updateCalc('+')}>+</button>

					<button onClick={deleteLast}>DEL</button>
				</div>

				<div className="digits">
					{createDigits()}
					<button onClick={() => updateCalc('0')}>0</button>
					<button onClick={() => updateCalc('.')}>.</button>
					<button onClick={calculate}>=</button>
				</div>
			</div>
		</div>
	);
Calculator in React

Calculation And Deletion

Now we are almost done, but our delete and equal button is not functional, so let’s make it functional. For that, we have created a function named calculate(). In this, we have added a simple line code setCalc(eval(calc).toString()); here eval will calculate the equation presented in the calc, and we just make in string value using toString method to update the calc value.

After that, in the deleteLast() function, if calc is blank then obviously we have nothing to do. We just delete the last value using the slice method, here -1 represents the deletion of one digit or ops from the end. then again, we will update the calc value to get a reflection on the screen. and we will update the result value since we need the dynamic result.

const calculate = () => {
		setCalc(eval(calc).toString());
	}

	const deleteLast = () => {
		if (calc == '') {

		}
		const value = calc.slice(0, -1);

		
		setCalc(value);
		setResult(eval(value).toString());
		
	}
Calculator in React

Full Source Code to Make Calculator in React

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

App.js

import { useState } from 'react';

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

	const ops = ['/', '*', '-', '+', '.'];

	const createDigits = () => {
		const digits = [];

		for (let i = 1; i < 10; i++) {
			digits.push(<button onClick={() => updateCalc(i.toString())} key={i}>{i}</button>);
		}

		return digits;
	}

	const updateCalc = (value) => {
		if (
			ops.includes(value) && calc === '' || 
			ops.includes(value) && ops.includes(calc.slice(-1))
		) {
			
			return;
		}
		
		setCalc(calc + value);

		if (!ops.includes(value)) {
			setResult(eval(calc + value).toString());
		}
	}

	const calculate = () => {
		setCalc(eval(calc).toString());
	}

	const deleteLast = () => {
		if (calc == '') {

		}
		const value = calc.slice(0, -1);

		
		setCalc(value);
		setResult(eval(value).toString());
		
	}

	return (
		<div className="App">
			<div className="calculator">
				<div className="display">
					<span>{result ? '(' + result + ')' : ''}</span> {calc || 0}
				</div>

				<div className="operators">
					<button onClick={() => updateCalc('/')}>/</button>
					<button onClick={() => updateCalc('*')}>x</button>
					<button onClick={() => updateCalc('-')}>-</button>
					<button onClick={() => updateCalc('+')}>+</button>

					<button onClick={deleteLast}>DEL</button>
				</div>

				<div className="digits">
					{createDigits()}
					<button onClick={() => updateCalc('0')}>0</button>
					<button onClick={() => updateCalc('.')}>.</button>
					<button onClick={calculate}>=</button>
				</div>
			</div>
		</div>
	);
}

export default App;

Index.css

:root {
	--primary: #d81e5b;
	--secondary: #8c38ff;
	--dark: #131a26;
	--light: #EEE;
}

* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
	font-family: 'Fira Sans', sans-serif;
}

body {
	background-color: var(--light);
}

.App {
	display: flex;
	min-height: 100vh;
	align-items: center;
	justify-content: center;
}

.calculator {
	width: 100%;
	max-width: 400px;
	background-color: #FFF;
	border-radius: 16px;
	overflow: hidden;
	box-shadow: 0px 2px 64px rgba(0, 0, 0, 0.2);
}

.display {
	padding: 16px;
	text-align: right;
	background-color: var(--dark);
	color: var(--light);
	font-size: 24px;
	font-weight: 300;
}

.display span {
	font-size: 14px;
	color: #888;
}

.operators {
	display: flex;
}

button {
	appearance: none;
	outline: none;
	border: none;
	color: #FFF;
	padding: 16px;
	font-size: 20px;
	cursor: pointer;
	transition: 0.4s;
}

button:hover {
	opacity: 0.9;
}

.operators button {
	flex: 1 1 0%;
	background-color: var(--primary);
	font-weight: 700;
}

.digits {
	display: flex;
	flex-wrap: wrap;
}

.digits button {
	flex: 1 1 33.333%;
	max-width: 33.333%;
	background-color: var(--dark);
}

Output

Calculator in React

Check out video reference here:

You may also like:

Reactjs Guru
Reactjs Guru

Welcome to React Guru, your ultimate destination for all things React.js! Whether you're a beginner taking your first steps or an experienced developer seeking advanced insights.

React tips & tutorials delivered to your inbox

Don't miss out on the latest insights, tutorials, and updates from the world of ReactJs! Our newsletter delivers valuable content directly to your inbox, keeping you informed and inspired.

Leave a Reply

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

Table of Contents