1 - Simple Counter App

Description

Create a React application that displays a simple counter. The counter should initially display 0 and have two buttons to increment or decrement the count. The count should update accordingly when a button is clicked.

Algorithm

  1. Initialize a state variable to store the count, set to 0.

  2. Render the current count to the screen.

  3. Create two buttons for incrementing and decrementing the count.

  4. Define functions to update the state variable when a button is clicked.

  5. Attach these functions to the respective button's onClick event.

Classes

Counter: A React component that manages the count state and renders the count and buttons.

Code

import React, { useState } from 'react';

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

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

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleIncrement}>+</button>
      <button onClick={handleDecrement}>-</button>
    </div>
  );
}

export default Counter;

Explanation

The code defines a Counter component that utilizes the useState hook to initialize a state variable count to 0. Two functions, handleIncrement and handleDecrement, are defined to update the count state variable. The component renders the current count and two buttons. The handleIncrement and handleDecrement functions are attached to the respective button's onClick event, enabling the updating of the count when a button is clicked.

Further Possible Enhancements

  • Implement a limit to the count (e.g., prevent it from going below 0 or above a certain number).

  • Display the count history or a list of previous counts.

  • Allow users to input a custom increment or decrement value.

  • Add a reset button to set the count back to 0.

Last updated