Simple way to build a Counter Functionality with ReactJS
Having counter buttons is very common in web apps like ecommerce app, etc. This functionality helps users to be able to increase or decrease a number of items. In this article, I will be sharing a very simple way to build this, using a product page as a use case. Of course, this knowledge can be helpful in some other projects.
The Steps
Install your react and tailwind CSS. I used
ReactJS
andTailwind CSS
in building this. To install,💡Create a folder on your desktop or anywhere in your PC💡Open that same folder in Visual Studio Code, then open your Terminal with shortcut CTRL + J. In your terminal, type in💡npm create vite@latest💡Put a dot . for project name so it creates automatically💡Select react (for select framework)💡Select JavaScript (for select variant)💡Then, type in npm install, and then npm run dev afterwardsAll of these steps can be found in the react documentation. For tailwind CSS installation you can follow the process here.
So, let’s get started with the build.
After building the structure of your app and styling, how do we make it work?
See below a snippet of mine
-
To make the increase and decrease button functional, create a
counter
function usinguseState
. TheuseState
hook allows us to manage state within our component. In this case, we'll use it to track the current count value. We will initialize the state to 1, which represents the minimum quantity. You can adjust this value as needed e.g. set it to 0 for a minimum quantity of zero. const [counter, setCounter] = useState(1); const increment = () => { setCounter(counter + 1); }; const decrement = () => { if (counter > 0) { setCounter(counter - 1); } };
With our variable name being
counter
andsetCounter
. OuruseState
has an initial value of 1The incremental and decremental function is set to +1 and -1. You can always change this to be +2, +3, etc. depending on the increase and decrease progression you want on every click.
After this, you go to where the count value is, in this case, our
p
tag and include {counter} to display the count value automatically.<div className='py-2 px-4 rounded-lg bg-[#eeeeee] border-[#dddddd] min-w-fit' onClick={decrement}> <FontAwesomeIcon icon={faMinus} /> </div> <p className='font-semibold text-xl'> {counter} </p> <div className='py-2 px-4 rounded-lg bg-[#eeeeee] border-[#dddddd] min-w-fit' onClick={increment}> <FontAwesomeIcon icon={faPlus} /> </div>
Testing our app
Ensure your changes is being saved. Go to your live server and test. You should see the Counter App rendered on the screen with an initial count and the two buttons to increase and decrease the count.
Clicking the Increase button or icon will increase the count, and clicking the Decrease will decrease it. The updated count value will be displayed on the screen.
Congratulations! You have successfully built a simple counter app using ReactJS.
You can view my live build here https://ecommerce-counter-orpin.vercel.app/