Skip to content
Advertisement

Counter inside an onClick function

I have a button that adds a new div (onClick). I want to add +1 to cargoNumberCounter so that it shows that it’s a new div.

  const [addReference, setAddReference] = useState([])
  const [cargoNumberCounter, setCargoNumberCounter] = useState(1)

  const createNewRef = () => {
    setCargoNumberCounter(cargoNumberCounter + 1)

    const newRef = (
      <div>
          <Heading>
             Cargo # {cargoNumberCounter}
            // {cargoNumberCounter.map((num, i) => (
            //  <p key={i}>Cargo # {num}</p>
            // ))}
          </Heading>
          <Button onClick={createNewRef}>
             Add more cargo
          </Button>
      </div>
    )

    setAddReference((ref) => [...ref, newRef])
  }

I thought I could make it work like I have shown in the example, or by spreading the state like so setCargoNumberCounter([...cargoNumberCounter, cargoNumberCounter +1]), but for some reason it doesn’t work.

Any thoughts on how to add +1 to each new div ?

Advertisement

Answer

It sounds like you may be better off with one button to add new items of cargo to the list. Here’s a quick example.

const { useState } = React;

function Example() {

  // Simple counter in state. You may prefer this to be 
  // an array, or an object that you can add item objects to
  const [counter, setCounter] = useState(0);

  // Returns an array of divs based on the counter value
  function getDivs() {
    const divs = [];
    for (let i = 0; i < counter; i++) {
      divs.push(<div>{i + 1}</div>);
    }
    return divs;
  }

  // Updates the counter
  function handleClick() {
    setCounter(counter + 1);
  }

  return (
    <div>
      <div className="divs">
        {getDivs()}
      </div>
      <div className="counter">Div count: {counter}</div>
      <button type="button" onClick={handleClick}>
        Add new div
      </button>
    </div>
  );

}


ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
.divs { border: 1px solid #676767; padding-left: 0.3em; }
.divs, .counter { margin-bottom: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement