1 - Simple Counter App

Description

Develop a React application that displays a counter with two buttons: one labeled "Increment" and one labeled "Decrement." Clicking the "Increment" button should increase the counter's value by 1, while clicking the "Decrement" button should decrease it by 1. The current counter value should be displayed clearly on the screen.

Algorithm

  1. State Management: Utilize React's useState hook to manage the counter value as a state variable. Initialize the state with an initial value (e.g., 0).

  2. Button Functionalities: Define separate functions for handling click events on the "Increment" and "Decrement" buttons. Each function should update the counter state by 1 (increment) or -1 (decrement) using the setState method.

  3. Counter Display: Render the current counter value, retrieved from the state variable, within a dedicated UI element such as a <span> or a <p> tag.

Code

CounterApp.ts

import React, { useState } from 'react';

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

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

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

  return (
    <div className="counter-app">
      <h1>Counter</h1>
      <span className="counter-value">{count}</span>
      <button onClick={handleIncrement}>Increment</button>
      <button onClick={handleDecrement}>Decrement</button>
    </div>
  );
}

export default CounterApp;

Explanation

  • useState Hook: useState creates a state variable count with an initial value of 0 and a setter function setCount to update its value.

  • Button Functions: handleIncrement and handleDecrement react to button clicks, adding or subtracting 1 from the count state, respectively.

  • Counter Display: The current count value is displayed within a <span> with the class "counter-value."

  • UI Components: Classes like "counter-app" and "counter-value" provide basic styling for the components.

Additional Notes

  • This code implementation serves as a basic example. You can extend it further by adding features like:

    • Setting custom initial counter values.

    • Implementing minimum and maximum limits for the counter.

    • Adding visual effects upon increment or decrement.

Last updated