Author avatar

Gaurav Singhal

How to Build a Basic Form Calculator in React.js

Gaurav Singhal

  • May 31, 2020
  • 9 Min read
  • May 31, 2020
  • 9 Min read
Web Development
Front End Web Development
Client-side Framework


React is well known for handling forms and updating DOM smoothly. Both these capabilities provide a great opportunity for developers to practice their React skills by building a simple form calculator. In this guide, you'll learn how to build a basic form calculator without any external libraries by merely utilizing the core concepts of React, JavaScript, and DOM manipulation.


For simplicity, the calculator will have only one function: the addition of two numbers. It will have two form fields: one for taking in the current number and the other a read-only input field for displaying the result. As most calculator apps are dynamic, the result field will show the current value of the sum, and any number of additions can be performed at one time. The form will contain two buttons: the add button and the clear button. The add button will add the current number to the sum, and the clear button will reset the form fields, as the names indicate.


Follow the steps below to create the calculator.


Make sure you have Nodejs and npm installed in your machine (at least version 8 or higher) along with a code editor and a web browser (preferably Chrome or Firefox).

Create a new project using create-react-app:

1npx create-react-app react-form-calculator

Cleaning up the Template

Remove the logo, App.css, and all their imports from App.js. Clean out the starter template inside the App component. Your App.js should look like this:

1import React from 'react';
2import './App.css';
4function App() {
5  return(
6      <div className="App">          
7     </div>
8  )
11export default App;

Creating the Form

Create a <form> with two <input> fields, one for displaying the result and the other for taking input from the user. Next, add two buttons to perform add and clear operations.

1import React from 'react';
2import './App.css';
4function App() {
5  return (
6    <div className="App">
7      <div className="app-title">
8        <h1> Basic Form Calculator</h1>
9      </div>
10      <form>
11            <input type="text" id="result" readOnly />   
12            <input type="text" id="num" placeholder="enter a number" />
13            <button>Add</button>
14            <button>Clear</button>
15      </form>
16    </div>
17  );
19export default App;

Calculator Form's State

Import useState from React to use state variables in a functional component.

1import React,{useState} from 'react';

The calculator form will have two state variables: one for storing the current value of the sum and the other for toggling the clear flag. Since the result is always expected to be a number, the currentSum can be initialized with 0 and clear can be set to false.

2    const [currentSum,setCurrentSum]=useState(0);
3    const [clear,setClear]=useState(false);

The Add Function

Take in the event object and call preventDefault() on it to prevent the page from reloading when the form submits. Whenever the user clicks the add button, the form needs to know that the addition function has to be performed. Toggle the clear flag false and get the current number entered by the user. As a simple validation to ensure that an empty value doesn't break the code, exit the flow if the user hits the add button without entering any number. Use parseInt() to parse the input string to an integer and add it to currentSum. Finally, clear the input field for the next number to be entered.

2const Add=(e)=>{
3    e.preventDefault();
4    if(clear) setClear(false);
5    let currentNum=document.querySelector('#num').value
6    if(currentNum=='')
7    return;
8    let sum= currentSum+parseInt(currentNum);
9    setCurrentSum(sum);
10    document.querySelector('#num').value="";

The Clear Function

Inside the clear function, simply reset the form and set the state variables to their appropriate values by setting the clear flag to true and currentSum to 0.

2 const Clear=(e)=>{
3    e.preventDefault();
4    console.log('sum:', currentSum);
5    document.querySelector('form').reset();
6    setClear(true);
7    setCurrentSum(0);
8  }

To ensure that the result field is empty when the app initially loads or Clear() is invoked, set this field's value to an empty string inside the useEffect hook when the component first mounts and whenever the clear flag is set to true.

2  useEffect(()=>{
3    document.querySelector('#result').value="";
4  },[])
6  useEffect(()=>{
7    if(clear)
8    document.querySelector('#result').value="";
9  })

Finally, your App.js should look like this:

1import React,{useState, useEffect} from 'react';
2import './App.css';
4function App() {
5  const [currentSum,setCurrentSum]=useState(0);
6  const [clear,setClear]=useState(false);
8  useEffect(()=>{
9    document.querySelector('#result').value="";
10  },[])
12  useEffect(()=>{
13    if(clear)
14    document.querySelector('#result').value="";
15  })
17  const Add=(e)=>{
18    e.preventDefault();
19    if(clear) setClear(false);
20    let currentNum=document.querySelector('#num').value
21    if(currentNum=='')
22    return;
23    let sum= currentSum+parseInt(currentNum);
24    setCurrentSum(sum);
25    document.querySelector('#num').value="";
27  }
29  const Clear=(e)=>{
30    e.preventDefault();
31    console.log('sum:', currentSum);
32    document.querySelector('form').reset();
33    setClear(true);
34    setCurrentSum(0);
35  }
37  return (
38    <div className="App">
39      <div className="app-title">
40        <h1> Basic Form Calculator</h1>
41      </div>
42      <form>
43            <input type="text" id="result" value={currentSum}  readOnly />   
44            <input type="text" id="num" placeholder="enter a number" />
45            <button onClick={Add}>Add</button>
46            <button onClick={Clear}>Clear</button>
47      </form>
48    </div>
49  );
52export default App;


Inside the root directory, run:

1npm start

This will spin up a local development server (usually on port 3000) and you can see your basic form calculator on the page. It will perform the addition of any two integers and reset these calculations when you click the clear button.

Improvising the App

There are many ways you can explore beyond this guide and make some improvisations to the app.

Updating the UI

You can use any CSS framework to give this form a more intriguing design and interface. You can take direct inspiration from the calculator app on your phone and try making an exact replica of it through some custom styling.

Extending the Features

Similar to the way addition was performed, you can extend this app to perform other basic mathematical calculations, such as subtraction, multiplication, division, etc. For incorporating more advanced features, JavaScript's Math object provides a plethora of math functions that you can use right out of the box.

Setting Validations and Alerts

A great user experience is always accompanied by some meaningful feedback to the user. You can set validations wherever necessary and add alerts to let users know about current processes, errors, or events when the app is in play.

Using a Keypad Component

To make it look like an actual calculator, you can use a keypad component instead of an input field. This can be a separate component rendered as a child in App.js. It also eliminates the need to set validation on the input field for entering anything other than an integer.

Converting to a Progressive Web App

React provides convenient ways to convert any single page app into a progressive web app to give a more native feel to the user. You can try converting it into a progressive web app so it lands on mobile devices as a pseudo native app and not the traditional web app.

Breaking Down into Components

You can redefine the architecture of your app by breaking it down into reusable components. For instance, you can create a separate component for handling the result, one for the keypad, and further inside the keypad a separate component for buttons.


Forms, when made into controlled components, can be used in a number of ways. As a developer, you should be able to code regular JavaScript easily in React to simplify development patterns and interact with the DOM conveniently. In this guide, you learned how to use a basic form in React as a calculator and how to extend and improve it so you can eventually add it to your dev portfolio!