Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Build a Basic Form Calculator in React.js

May 31, 2020 • 9 Minute Read

Introduction

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.

Approach

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.

Implementation

Follow the steps below to create the calculator.

Setup

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:

      npx 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:

      import React from 'react';
import './App.css';

function App() {
  return(
      <div className="App">          
     </div>
  )
}

export 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.

      import React from 'react';
import './App.css';

function App() {
  return (
    <div className="App">
      <div className="app-title">
        <h1> Basic Form Calculator</h1>
      </div>
      <form>
            <input type="text" id="result" readOnly />   
            <input type="text" id="num" placeholder="enter a number" />
            <button>Add</button>
            <button>Clear</button>
      </form>
    </div>
  );
}
export default App;
    

Calculator Form's State

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

      import 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.

      ...
    const [currentSum,setCurrentSum]=useState(0);
    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.

      ...
const Add=(e)=>{
    e.preventDefault();
    if(clear) setClear(false);
    let currentNum=document.querySelector('#num').value
    if(currentNum=='')
    return;
    let sum= currentSum+parseInt(currentNum);
    setCurrentSum(sum);
    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.

      ...
 const Clear=(e)=>{
    e.preventDefault();
    console.log('sum:', currentSum);
    document.querySelector('form').reset();
    setClear(true);
    setCurrentSum(0);
  }
...
    

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.

      ...
  useEffect(()=>{
    document.querySelector('#result').value="";
  },[])

  useEffect(()=>{
    if(clear)
    document.querySelector('#result').value="";
  })
...
    

Finally, your App.js should look like this:

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

function App() {
  const [currentSum,setCurrentSum]=useState(0);
  const [clear,setClear]=useState(false);

  useEffect(()=>{
    document.querySelector('#result').value="";
  },[])
  
  useEffect(()=>{
    if(clear)
    document.querySelector('#result').value="";
  })

  const Add=(e)=>{
    e.preventDefault();
    if(clear) setClear(false);
    let currentNum=document.querySelector('#num').value
    if(currentNum=='')
    return;
    let sum= currentSum+parseInt(currentNum);
    setCurrentSum(sum);
    document.querySelector('#num').value="";
      
  }

  const Clear=(e)=>{
    e.preventDefault();
    console.log('sum:', currentSum);
    document.querySelector('form').reset();
    setClear(true);
    setCurrentSum(0);
  }

  return (
    <div className="App">
      <div className="app-title">
        <h1> Basic Form Calculator</h1>
      </div>
      <form>
            <input type="text" id="result" value={currentSum}  readOnly />   
            <input type="text" id="num" placeholder="enter a number" />
            <button onClick={Add}>Add</button>
            <button onClick={Clear}>Clear</button>
      </form>
    </div>
  );
}

export default App;
    

Testing

Inside the root directory, run:

      npm 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.

Conclusion

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!

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author