How to create a counter in React Js

A counter is nothing but a number with two buttons. One to increment its value, other to decrement. It is similar to the carts section in the shopping apps. In this tutorial, we will learn how to create a counter in React Js.

Create a counter in React Js

We will create a functional component and use the useState hook. You can go through React hooks here.

What is useState() hook in ReactJs?

What is the useEffect() hook in React Js?

We will create one state variable called count and two buttons. The code for which will look like this.

import React,{useState} from 'react'

const App = () => {
  const[count,setCount]=useState(0);
  return (
    <div>
      <button>+</button>
      {count}
      <button>-</button>
    </div>
  )
}

export default App

The output would look like this:

how to create a counter in react js

We are not doing any styling though you can add some of your choices. So, now we have to add two functions. One will increase the value of count by 1 whereas the other will decrease the value of count by 1. We will pass these functions in the onClick method of the two buttons. The code will look like this.

import React,{useState} from 'react'

const App = () => {
  const[count,setCount]=useState(0);
  const inc=()=>{
    setCount(count+1);
  }
  const dec=()=>{
    setCount(count-1);
  }
  return (
    <div>
      <button onClick={inc} >+</button>
      {count}
      <button onClick={dec}>-</button>
    </div>
  )
}

export default App

This looks fine. Count increases by 1 on clicking ‘+’ and decreases by 1 on clicking ‘-‘. Although, there is one thing wrong with this. After clicking ‘-‘ multiple times, the count may become negative. We do not want this. So, we will check with an if condition. If the count is less than 0 then do nothing. The code will look like this.

import React,{useState} from 'react'

const App = () => {
  const[count,setCount]=useState(0);
  const inc=()=>{
    setCount(count+1);
  }
  const dec=()=>{
    if(count>0)
    setCount(count-1);
  }
  return (
    <div>
      <button onClick={inc} >+</button>
      {count}
      <button onClick={dec}>-</button>
    </div>
  )
}

export default App

Now our app is perfect. If you click on ‘-‘ after the count is 0 then nothing will happen. You can even add some styling and make the ‘-‘ button disabled after that. You can add a similar upper bound condition if you want to. The basic logic remains the same.

Conclusion:

This is how easy it is to create a counter. You can use the same concept in a shopping cart.

Leave a Reply

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