DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 8

Today's task is to create the famous counter app, with the following instructions:

  1. The counter should start from 0
  2. Click the "+" button to increment
  3. Click the "-" button to decrement

The boilerplate code for this:

import React from 'react'

export function App() {
  return (
    <div>
      <button data-testid="decrement-button">-</button>
      <button data-testid="increment-button">+</button>
      <p>clicked: 0</p>
    </div>
  )
}

Enter fullscreen mode Exit fullscreen mode

First, declare the variables to change the state of the value to be increased and decreased.

const[count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

Then create the functions to increase and decrease the count

const handleIncrease = () => {
   setCount(count + 1);
}
const handleDecrease = () => {
  setCount(count - 1);
}

Enter fullscreen mode Exit fullscreen mode

Finally, add the functions to the respective buttons, then update the state

<button onClick={handleDecrease} data-testid="decrement-button">-</button>
<button onClick={handleIncrease} data-testid="increment-button">+</button>
<p>clicked: {count}</p>

Enter fullscreen mode Exit fullscreen mode

The final output looks like this:


import React, {useState} from 'react'

export function App() {
  const [count, setCount] = useState(0);

  const handleIncrease = () => {
    setCount(count + 1);
  }
  const handleDecrease = () => {
    setCount(count - 1);
  }
  return (
    <div>
      <button onClick={handleDecrease} data-testid="decrement-button">-</button>
      <button onClick={handleIncrease} data-testid="increment-button">+</button>
      <p>clicked: {count}</p>
    </div>
  )
}

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)