Building a Calculator With React

React.js is currently the most popular library out of all the JavaScript libraries and frameworks. Additionally, it is part of one of the top tech stacks for building full stack applications, the MERN stack. React allows you to build single-page applications that are efficient, maintainable, and scalable.

If you haven’t already, I suggest checking out my first post on React.js here. This will give you a basic understanding of the benefit React provides and why it is used. Additionally, I give you the bare minimum to create your first basic React app and see it in the browser.

The Project

In this post, I will be walking you step-by-step through building a calculator with React that will allow you to perform common operations. It will be similar to the standard one that’s already built into Windows (with a few less options).

If you want to skip ahead and see the final source code, you can do so here.

Getting Started

Like I said, I already talked some about the basics of getting a React app up and running in an earlier post. I will mention some of the same things here again so that it is all consolidated in one place.

First, you’re going to want to have Node.js and npm installed on your machine. At the time of writing this post, the latest versions of Node and npm are 18.13.0 and 8.19.3, respectively.

After Node/npm are installed, open a console and navigate to where you want to save your project. Lately, I’ve been saving my projects in C:\Code, but everyone has their own preferences. In the console, run:

Create Project Command

    1. npx create-react-app calculator-app will create the boilerplate for a React application and put it in the calculator-app folder.
    2. cd calculator-app will navigate to the calculator-app folder.
    3. npm start will run the application.

You should now see the application load in the browser:

React Application

Creating the Foundation

To start building our application, we’re going to delete the src folder and recreate it from the ground up:

Delete src Folder

Inside the new src folder, create an App.js file:

Create App.js

App.js is the file for the App component, also the main component. The App component is a container for all other components.

Additionally, inside the src folder, create a file called index.js:

Create index.js

index.js is the entry point for all node apps. In React, it just has code of what to render and where to render it.

Save the changes and restart the application by pressing Ctrl+C in the terminal and running npm start again. You should now see “Hello world!” displayed in the browser. This doesn’t relate to our calculator app, but this is a simple way to test that everything is working.

Creating the UI

Now, let’s change App.js:

Our app should now look like this:

Calculator 1

useState is what as known as a Hook in React. Introduced in React 16.8 (we’re on version 18.2 at the time of writing this post), the State Hook allows us to keep track of data in our components with minimal code.

Let’s create another file in our src folder, App.css:

Create App.css

Let’s bring that into our App.js:

Import App.css

With those changes, you should now see the app update with the lime background:

Calculator 2

Again, we’re not going to keep the CSS like this (but you can keep it lime if you want!). This is just to confirm we can successfully link our CSS and apply it. It’s good practice in software to make small changes at a time and test those changes along the way.

Now, update App.css to the following:

With that, the page should now look like a calculator:

Calculator 3

And our project should now look like this:

Project Architecture

Let’s make some more changes to App.js to improve the appearance of our calculator. Additionally, since we are using CSS grid, we will need to add a name property to most of our buttons. This will allow us to grab the text from the corresponding key that is pressed to append it to our calculator output. With those changes, our App.js will now look like this:

 

In the browser, our calculator should look like:

Calculator 4

Adding Functionality

To start adding functionality to the calculator, let’s add a function to App.js  called handleClick():

Next, let’s set the onClick event handler of all of our buttons to be the handleClick() function we just created:

Now, when a button is pressed, the results panel will update:
Calculator 5
The C, +/-, and % buttons will not affect the results panel because we did not give them a name attribute and our handleClick() method only cares about the name attribute.

Clear Screen/Capturing Last Expression

We can finally start adding the logic that will make this work like it’s supposed to. Let’s add a few more state variables and a clearResults() function to the top of the App() function (I’m pretty sure both of these would be called functions. Which means JavaScript allows functions within functions, something I realized only upon writing this post.):

I decided to use a variable lastExpression to store whatever is after the last operator the user entered. I needed this to be able to implement the +/- and % buttons; we will see this further down.

We can also set the onClick event handler of our C button to be the clearResults() method we just created:

Now, when the C button is pressed, our calculator will clear and our state will reset.

Build the Expression

We also want to replace our handleClick() method with a new method called buildExpression() in (it will do almost the same thing except now we will build out our lastExpression state variable also):

Next, we need to change all of our button’s onClick event handlers that were set to handleClick() to be set to buildExpression():

Calculation

To make our = button work, we need to add a few methods after buildExpression() and just before our return statement:

And we need to set the onClick handler of our = button to be calcResult():

With that, we can calculate our results now, and it is starting to work like an actual calculator. However, to make the app work correctly and be bug free, we must add two methods above calcResult():

changeOperator() will be called whenever the +, , ×, or ÷ buttons are clicked so let’s change their onClick handler:

Change Sign

We still need need to add functionality to a few other buttons. To make our +/- button work, we need to add a changeSign() function below buildExpression() and we need to change onClick of +/- to be changeSign():

Convert Expression to Percentage

Finally, for our percentage button, let’s add a makeExpressionPercent() function below our changeSign() and change our corresponding onClick in our JSX:

Conclusion

With that, our app is 100% working! I know I didn’t break down every function here and explain, but hopefully most of it is self explanatory. To challenge yourself further, try deleting all of the code from each method and reimplement them the way you would! You can get creative and maybe make the app have more than 19 buttons. It’s up to you. Once again, if you want to see the final source code, you can find it here.

I think this post will be helpful but I have mixed feelings about it. I always wondered, “Why do so many people make YouTube videos explaining how to build apps when they could just write an article or blog post?” As you may have seen here, it can get confusing updating the files as we go along without an idea of what the entire source should look like. That’s why I included the repo for the final code for reference and I tried to show the surrounding code blocks when we made changes so you’d have context of what line the new code should go on. I wanted to take this same approach to show you how a full stack application would be built, maybe breaking it up into multiple posts. I am not sure if I will now, we shall see. But in any case, I hope this post was helpful and if you have any questions, feel free to reach me via the contact page. And if you want to be notified when future posts drop, make sure to subscribe. Stay tuned!

 

1 Trackback / Pingback

  1. Debugging React Apps - Galen Casstevens

Comments are closed.