DEV Community

Lalit LP
Lalit LP

Posted on

React Counter App...

import React, { useState } from 'react';

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

  const handleIncrement = () => {
    setCount(count + 1);
  };

  const handleDecrement = () => {
    setCount(count - 1);
  };

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={handleIncrement} data-testid="plus-btn">+</button>
      <button onClick={handleDecrement} data-testid="minus-btn">-</button>
    </div>
  );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

In this solution, I've used the useState hook to declare a state variable for the current count. I've also defined two event handlers, handleIncrement and handleDecrement, that update the count using the setCount function.

In the return statement, I'm displaying the current count along with two buttons that call the event handlers when clicked. I've also added data-testid attributes to each button so that they can be tested using React Testing Library or a similar tool.

Top comments (0)