This is a simple calculator example written in react.js. You may need some basic understanding on JavaScript, CSS and React in order to do so. We will do this from the very beginning, i.e. by installing npm, creating a react app  etc.

In the very beginning, you need to install an code editor (here I used Visual Studio) then you need to install Node.js and NPM.

Setting up React environment

Now you can create a react application by installing the create-react-app by running this command in your terminal.

npm install -g create-react-app

Now to create a React application run the below command

cd <path_to_directory>
npx create-react-app myfirstreact

After successful execution of the above command, React will create a directory named ‘myfirstreact’. This directory will contain all of the default files of the application.

 Default files created by React
It shows the default files created by React for our application myfirstreact.

After the command has successfully executed now run the npm start command to use the React application

npm start
command for staring the React Application

A new browser window will open with your newly created react application. you can also open it in a browser by typing localhost:3000 in the address bar.

Newly created React page after create-react-app
Newly created React page after create-react-app

Now just replace the placeholder content of App.js and App.css with the given below content.



Here, I use react hook for implementation.

import React, { useState,useEffect,useRef } from 'react';import './App.css';function App() {  const [result,setResult]=useState("");  const inputRef=useRef(null);  useEffect(()=>inputRef.current.focus());     function handleclick(e){      setResult(result.concat(e.target.name));  }  function backspace(){    setResult(result.slice(0,result.length-1))  }  function clear(){    setResult("")  }  function calculate(){    try{      setResult(eval(result).toString());    }    catch(error){      setResult("Error");    }  }  return (    <div className="calc-app">    <form>      <input type="text" value={result} ref={inputRef}/>    </form>      <div className="keypad">        <button name="1" onClick={handleclick}>1</button>        <button name="2" onClick={handleclick}>2</button>        <button name="3" onClick={handleclick}>3</button>        <button name="+" onClick={handleclick}>+</button>        <button name="4" onClick={handleclick}>4</button>        <button name="5" onClick={handleclick}>5</button>        <button name="6" onClick={handleclick}>6</button>        <button name="-" onClick={handleclick}>-</button>        <button name="7" onClick={handleclick}>7</button>        <button name="8" onClick={handleclick}>8</button>        <button name="9" onClick={handleclick}>9</button>        <button name="*" onClick={handleclick}>*</button>        <button name="0" onClick={handleclick}>0</button>        <button name="/" onClick={handleclick}>/</button>        <button onClick={clear}>Clear</button>        <button onClick={backspace}>Back</button>            <button id="result" onClick={calculate}>Result</button>      </div>        </div>  );}export default App;
App.js code for React calculator


import React, { useState,useEffect,useRef } from 'react';import './App.css';

Whenever you want to use something, you need to import it first. If you want to make the component usable in other parts of the app, you need to export it after creation and import it in the file where you want to use it. We need to import this component and render it to our root App element, so we can see it in the browser.

Function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions.

const(i.e constant) that means the variables value won’t change.  

‘setResult’ returns a stateful value, and a function to update it. During the initial render, the returned state (result) is the same as the value passed as the first argument (initial state), Here initial result is (” “).

The ‘seResult’ function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

const inputRef=useRef(null); useEffect(()=>inputRef.current.focus()); 
React.js code to give default focus on a textbox 

This command is used to give focus on the text box by default which will display the content or the result.

function handleclick(e){      setResult(result.concat(e.target.name));  }
handleclick function to handle the key event in a calculator app

The function handleclick(e) is used to handle the event when number key and operator key pressed. It will set result as name of the button and concatenate with the previous one.

 function backspace(){    setResult(result.slice(0,result.length-1))  }
functionality of a back key in a calculator

The function backspace is used to handle the event when back button is clicked. It will set result from string 0 to length-1, i.e it will display one character less when back button is clicked.

function clear(){    setResult("")  }
functionality of a clear key in a calculator

The clear function is used to set the result as null. It will remove all from result and display nothing.

function calculate(){    try{      setResult(eval(result).toString());    }    catch(error){      setResult("Error");    }  }
code for evaluating result for a calculator

The function calculate() is used to handle the event when result button is clicked. It will evaluate the operation(or expression) using inbuilt function eval() and then converted it to a string. It will also handle error if some wrong expression is given and display an error massage.

Now we create buttons and a text box by using basic javascript code. And set the appropriate event Handler.

<form>    <input type="text" value={result} ref={inputRef}/></form>
code to display of the content of a calculator

In text box we set value as {result} because the text box will display whatever value is set on the variable result. And the reference is given as InputRef, In InputRef we set an effect i.e by default focus on the text box.


.calc-app {margin: 0 auto;margin-top: 40px;width: 256px;text-align: center;}.keypad{  display: grid;  grid-template-columns: repeat(4, 1fr);  grid-auto-rows: minmax(60px, auto);}input[type="text"]{  height: 60px;  width:250px;}#result{  grid-column:1/5;}
css code used in this calculator application

We use a basic CSS for the whole component i.e calc-app and for keypad, for the display box and for the result button. I will not go deep in CSS part as we are here to learn React.js

Final Output

Final look of the calculator
Final look of the calculator


We have built a simple React.js calculator from scratch, learned about setup environment and installation process using create-react-app package. Here we build some simple functionality such as addition, subtraction, multiplication and division. We can add more functionality and adding more CSS functionality it will look more nuance and attractive visually, but for a beginner this much is enough.

Here at Probyto, we use React.js for our frontend development.