Author avatar

Gaurav Singhal

How to Build a Basic Form Calculator in React.js

Gaurav Singhal

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

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:

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

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:

1
2
3
4
5
6
7
8
9
10
11
import React from 'react';
import './App.css';

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

export default App;
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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;
jsx

Calculator Form's State

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

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

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.

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

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
...
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="";

}
...
jsx

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.

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

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.

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

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

Finally, your App.js should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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;
jsx

Testing

Inside the root directory, run:

1
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!

2