counter_New counter

 import React, { useState } from 'react';


const Counter = () => {

  const [counters, setCounters] = useState([0]);


  // Function to add a new counter

  const addCounter = () => {

    setCounters([...counters, 0]);

  };


  // Function to handle increment

  const increment = (index) => {

    const newCounters = [...counters];

    newCounters[index] += 1;

    setCounters(newCounters);

  };


  // Function to handle decrement

  const decrement = (index) => {

    const newCounters = [...counters];

    if (newCounters[index] > 0) {

      newCounters[index] -= 1;

    }

    setCounters(newCounters);

  };


  return (

    <div>

      {counters.map((count, index) => (

        <div key={index} style={{ marginBottom: '10px' }}>

          <h3>Counter {index + 1}</h3>

          <button onClick={() => increment(index)}>Increase</button>

          <span style={{ margin: '0 10px' }}>{count}</span>

          <button onClick={() => decrement(index)}>Decrease</button>

        </div>

      ))}

      <button onClick={addCounter}>Add New Counter</button>

    </div>

  );

};


export default Counter;

Comments

Popular posts from this blog

Controlled Form

LOCAL STORE

NodeJS MongoDB