How to build a calculator app in React Js | React js calculator app | React calculator

calculator-app in react js
calculator-app in react js

Hi, welcome here In this tutorial, we will build a calculator app using react js. This is the complete tutorial on how to develop a calculator app in react js. The prerequisites for this project are as follows:

  • Node.js should be installed in your system.
  • Create a brand new ReactJs project. Just copy the code below:
				
					code to create reactjs project:

npx create-react-app my-app

and after it run:

cd my-app

and then install a npm package:

npm i prop-types
				
			

The brand-new React Js project should look like this:

brand new react js app
brand new react js app

Here is your code for the App.js file, copy the code below and paste it into your App.js file:

				
					import logo from './logo.svg';
import './App.css';
import ResultView from './components/ResultView';
import Keyboard from './components/Keyboard';
import { useState } from 'react';

let output = '';
let history = '';
let symbols = ['*', '-', '+', '/'];


function App() {
  const [state, setState] = useState({
    history: '',
    displayValue: ''
  });

  const updateState = () => {
    setState({history: history.toString(), displayValue: output.toString()})
  };

  const onClick = (id, keyType, value) => {
    output = output.toString();
    let lastInput = output.slice(-1);

    switch (keyType) {
      case 'function':
        functionKey(id, lastInput);
        break;
      case 'operator':
        operatorKey(value, lastInput);
        break;
      case 'number':
        numberKey(value, lastInput)
        break;
      default:
        return;
    }
  };

  const functionKey = (id, lastInput) => {
    const resetOutput = display => {
      output = ''
      history= ''
      display && updateState();
    };
    const calculate = lastInput=>{
      if(!symbols.includes(lastInput) && output) {
        try {
          history = output;
          output = eval(output.replace(/%/g, '*0.01'));
          output = Number.isInteger(output) ? output : output.toFixed(3);
          updateState();
          history = output;
          output = '';
        } catch (error) {
          output = 'Error';
          updateState();
          resetOutput();
        }
      }
    };
    switch (id) {
      case 'clear':
        resetOutput(true);
        break;
        case 'clearBack':
          output = output.slice(0, -1);
          updateState();
          break;
          case 'calc':
            calculate(lastInput);
            break;
        default:
          return;
    }
  };

  const operatorKey = (value, lastInput) => {
    if (output === '' && value !=='-') {
      return;
    } else {
      symbols.includes(lastInput) ? (output = output.slice(0, -1) + value) : (output += value);
    }
    updateState();
  };

  const numberKey = (value, lastInput) => {
    if(value === '.' || value ==='%') {
      if(output === '' && value === '%')
      return;
      lastInput === '.' || lastInput === '%' || (output += value);
    } else {
      output += value;
    }
    updateState();
  }




  return (
    <div className="app">
      <div className='container'>
        <h1 className='heading'>ReactCalculator</h1>
        <ResultView history={state.history}  output={state.displayValue}/>
        <Keyboard onClick={onClick} />
      </div>
    </div>
  );
}

export default App;

				
			

Here is your code for the App.css file, copy the code below and paste it into your App.css file:

				
					* {
	padding: 0;
	margin: 0;
	box-sizing: border-box;
}

#root {
	display: flex;
	justify-content: center;
	align-content: center;
	height: 100vh;
	padding: 20px;
	font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
	background: #dfe8f1;
}


.app {
	position: relative;
	z-index: 10;
	margin: auto;
	top: -10px;
	height: fit-content;
	width: 350px;
	border-radius: 10px;
	backdrop-filter: blur(12px);
	border-radius: 13px;
	background: linear-gradient(145deg, #eff8ff, #c9d1d9);
	box-shadow:  26px 26px 58px #7b8085,
				 -26px -26px 58px #ffffff;

}


.heading {
	text-align: center;
	padding-top: 20px;
	color: rgb(13, 33, 63);
}

.container {
	color: rgb(13, 33, 63);
}

.result {
	width: 300px;
	height: 140px;
	padding: 20px 30px;
	text-align: right;
	position: relative;
	overflow: hidden;
}

.result .history {
	font-size: 19px;
}

.result .output {
	font-size: 35px;
	bottom: 18px;
}

.result .history,
.result .output {
	right: 25px;
	width: 200vw;
	position: absolute;
	text-align: right;
}

.keyboard {
	/* display: -ms-grid; */
	display: grid;
	grid-template-columns: 1fr 1fr 1fr 1fr;
}

.keyboard div.btn {
	display: -ms-grid;
	display: grid;
	place-content: center;
	width: 100%;
	height: 75px;
	padding: 10px;
	user-select: none;
	cursor: pointer;
	border-bottom: 1px solid rgba(255, 255, 255, 0.02);
	border-right: 1px solid rgba(255, 255, 255, 0.02);
	font-size: large;
	font-weight: 500;
}

.keyboard div.btn#clear {
	grid-column-start: 1;
	grid-column-end: 3;
}

.keyboard div.btn:hover {
	transition: 0.2s;
	background: rgba(0, 0, 0, 0.05);
}

.keyboard div.btn:active {
	transition: 0.2s;
	background: rgba(0, 0, 0, 0.20);
}
				
			

After it, make a new folder in the src and name it ‘components’. In the components folder, we are going to build two components for our calculator app. The first one will be Keyboard.jsx and the second one will be ResultView.jsx and copy the code below, and past it to into corresponding components:

Here is your code for the Keyboard.jsx file:

				
					import React from 'react'
import PropTypes from 'prop-types'

const keys = [
    { id: 'clear', class: 'function', value: 'Clear' },
    { id: 'clearBack', class: 'function', value: 'Backspace' },
    { id: 'multiply', class: 'operator', value: '*' },
    { id: '9', class: 'number', value: '9' },
    { id: '8', class: 'number', value: '8' },
    { id: '7', class: 'number', value: '7' },
    { id: 'minus', class: 'operator', value: '-' },
    { id: '6', class: 'number', value: '6' },
    { id: '5', class: 'number', value: '5' },
    { id: '4', class: 'number', value: '4' },
    { id: 'add', class: 'operator', value: '+' },
    { id: '3', class: 'number', value: '3' },
    { id: '2', class: 'number', value: '2' },
    { id: '1', class: 'number', value: '1' },
    { id: 'divide', class: 'operator', value: '/' },
    { id: 'dot', class: 'number', value: '.' },
    { id: '0', class: 'number', value: '0' },
    { id: '%', class: 'number', value: '%' },
    { id: 'calc', class: 'function', value: '=' }
];

const Keyboard = ({onClick}) => {


    return (
        <div className='keyboard'>
            {
                keys.map(key => (
                    <div
                    className='btn'
                    id={key.id}
                    key={key.id}
                    onClick={()=> onClick(key.id, key.class, key.value)}
                    >
                        {key.value}
                    </div>
                ))
            }
        </div>
    )
}

Keyboard.propTypes = {
    onClick: PropTypes.func
}
export default Keyboard
				
			

Here is your code for the ResultView.jsx file:

				
					import React from 'react'
import PropTypes from 'prop-types'

const ResultView = ({history, output}) => {

    // now we are going to change the text color to red if there will be any error

    let ColorStyle = {
        color: output === 'Error' ? '#f11' : '#0d213f'
    };
  return (
    <div style={ColorStyle} className="result">
        <div className='history'>{history}</div>
        <div className='output'>{output}</div>
    </div>
  )
}

ResultView.propTypes = {
    history: PropTypes.string,
    output: PropTypes.string
}

export default ResultView
				
			

After writing the code into the files (don’t forget to save it ,) you can run the command below:

				
					npm run start