How to Create a Simple Counter App Using ReactJS?

How to Create a Simple Counter App Using ReactJS?

Overview

Creating a simple counter app can be an excellent practice for learning about event handling in ReactJS. But counting is not just a simple game to learn the basics about ReactJS. No! Sometimes, it is an essential part of a web application, like when you may want to measure page views, the number of times your user focused on a form element, or count any other reactions to your content.

In this quick advanced tutorial, I will provide a straightforward roadmap showing the steps of creating different counter apps. Then, I will also give you two example codes you may like to use in your projects.

Ready? Let’s get started!

Algorithm

Making a simple counter app with reactJS has a process that you can follow step by step:

  1. Create the app itself
  2. Make a component for the counter
  3. Build the UI
  4. Define what you want to count and use ReactJS functions to count them
  5. Save or use the calculated numbers

Now, let’s make our first ReactJS counter app with this algorithm.

Example 1 – Simple Click Counter

Follow the steps below:

Step 1 – Create a React App

After you have installed the prerequisites of ReactJS development, in order to create a basic app, you can open CMD and simply run the command below in your desired path.

npx create-react-app YourAppNameHere

It will take a few minutes to complete, and your app will be ready for editing.

Step 2 – Create the Counter Component

After you open the app folder in any IDE (like VSCode), please right-click the src directory in your project root and create a new JS file inside it. It will be considered as a component for your counter. I named it Counter.js.

Then, please replace the codes below in the Counter.js file.

import React from "react";

const Counter = () => {
    return (<div> Hello World </div>)
}

export default Counter

It is just some simple JSX codes. First, we imported the React library, then made a component with an arrow function, and finally exported it to be accessible outside the file.

Now, replace the codes below with what you already have inside the App.js file. It will make your component visible in your app.

import logo from './logo.svg';
import './App.css';
import Counter from './Counter';
function App() {
  return (
    <div>
      <Counter />
    </div>
  );
}

export default App;

You can see above that the only component we have assigned to our app is Counter.js.

Step 3 – Complete the UI

Now, your app showcases a ‘Hello World’ string we wrote in our component. So, go ahead and add some more elements to the UI. To do that, please get back to the Counter.js file and edit it as below.

import React from "react";

const Counter = () => {
    return (
        <div className="Main-div">
            <section>
                <button className="Add-button">Add Number</button>
                <button className="Remove-button">Remove Number</button>
                <button className="Reset-button">Reset Numbers</button>
                <p className="Num">Numbers: 0 </p>
            </section>
        </div>
    )
}

export default Countertwo

You can also add some custom CSS to the App.css file to improve your design.

.Main-div {
  background-color: #e2e2e2;
  padding: 30px 30px 30px 30px;
  width: 600px;
  margin: 50px auto;
  border-radius: 10px;
}

.Num {
  float: right;
}

.Add-button {
  margin-right: 10px;
  background-color: blue;
  color: white;
  padding: 10px;
  border-radius: 5px;
  cursor: pointer; 
}
.Remove-button {
  background-color: red;
  color: white;
  padding: 10px;
  border-radius: 5px;
  cursor: pointer;
}

.Reset-button {
  margin-left: 10px;
  background-color: green;
  color: white;
  padding: 10px;
  border-radius: 5px;
  cursor: pointer;
}

Now, if you look at the app, you’ll find that it is just a static and non-functional user interface.

So, let’s go through the challenging part: add some functionality to the app and make it dynamic.

Step 4 – Define What You Want to Count

In the first example, we aim to simply count the times a user clicks a button. So, what we are going to do is to create a function that handles this responsibility. Replace the codes below with what you already have in your Counter.js file.

import React, { useState } from "react";

const Countertwo = () => {
    const [number, setNumber] = useState(0)

    const AddNumber = () => {
        setNumber((number) => {
            return number + 1
        })
    }

    const ResetNumbers = () => {
        setNumber((number) => {
            return number = 0
        })
    }

    const RemoveNumber = () => {
        if (item != 0) {
            setNumber((number) => {
                return number - 1
            })
        }  
    }

    return (
        <div tabIndex={0} onKeyDown={handleKeyDown} className="Main-div">
            <section className="btns">
                <button className="Add-button" onClick={AddNumber}>Add Number</button>
                <button className="Remove-button" onClick={RemoveNumber}>Remove Number</button>
                <button className="Reset-button" onClick={ResetNumbers}>Reset Numbers</button>
                <p className="Num">Numbers: {number}</p>
            </section>
        </div>
    )
}

export default Countertwo

In this part, first, we made a variable named number and used the useState() updater hook to manage its amount. Then, you need to add three functions. The first one, like its name AddNumber, is responsible for adding one number to the output. Then, to connect this function with the first button, use an onClick event handler, as shown in the code above. We also did the same for the ResetNumbers and RemoveNumber functions.

Your app is alive now! Take a look at it and try to use the buttons.

Step 5 – Save the Result

Now that you have counted an action in your app, you can do anything with the result obtained. First, you need to temporarily save the result in a global variable, and after that, you can transfer it to your database, simply alert it, or use it anywhere you like.

var result = 0;
    const SaveNumber = () => {
        result = number;
        alert(result);
    }

In the same way as before, you can run this function under a new button.

<button className="Save-button" onClick={SaveNumber}>Save Number</button>

Example 2 – Pressed Keys Counter

As mentioned earlier, you can count other events on your ReactJS app. In this example, I will provide another component that will measure the times a user presses a button on the keyboard. It will help you become more familiar with the algorithm for creating a counter app.

Steps 1, 2, and 3 – Create an app, a Component, and a UI

Create a new component in your ReactJS app and name it Countertwo.js. Then, paste the codes below inside it.

import React, { useState } from "react";

    const [pressedkey, setPresedkey] = useState(0)

    const handleKeyDown = event => {
        setPresedkey ((pressedkey) => {
            return pressedkey + 1
        })
    }

    const ResetKeys = event => {
        setKeypressed((pressedkey) => {
            return pressedkey = 0   
        })
    }

    return (
        <div tabIndex={0} onKeyDown={handleKeyDown} className="Main-div">
            <section className="Keycounter">
                <button className="Reset-key-numbers" onClick={ResetKeys}>Reset PressedKey Counter</button>
                <p className="Num">Key Pressed: {keypressed}</p>
            </section>
        </div>
    )
}

export default Countertwo

It has the same syntax as the previous component. The first constant is a state handler. After that, you can see two simple functions for adding and resetting the result. Ultimately, we made the UI inside the return section and simply exported the whole component.

Don’t forget to give it some styles from the App.css file.

.Main-div {
  background-color: #e2e2e2;
  padding: 30px 30px 30px 30px;
  width: 600px;
  margin: 50px auto;
  border-radius: 10px;
}

.Keycounter {
  margin-top: 25px;
}

.Reset-key-numbers {
  background-color: green;
  color: white;
  padding: 10px;
  border-radius: 5px;
  cursor: pointer;
}

Then, add the component to the App.js so that it can be visible on the browser.

import logo from './logo.svg';
import './App.css';
import Countertwo from './Countertwo';

function App() {
  return (
    <div>
      <Countertwo />
    </div>
  );
}

export default App;

That’s it! Now, your app will look like the screenshot below, which will count the number of keys you press on your keyboard.

One Step Further

If you want to practice more counting applications with ReactJs, we suggest you count the user focus on an element like a text input. Try to count the focuses using the onFocus event handler and count the times they click outside of the element using the onBlur attribute.

You can also be creative, find another idea, and try making a counter app with that idea.

Conclusion

This tutorial taught us how to create different counter apps using ReactJS. We created a click counter and a pressed-key counter and finally got an idea of how to use the calculated results.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *