'ReactJS for loop create buttons and set variable according to the integer in the loop

I am new to ReactJS, I am trying to create 10 buttons with for loops, and set a variable with the integer from the for loop, however the function setMqty(i) always returns 11 for all the buttons. What is the correct way for doing this?

  var qtyButtons = [];
  for(var i = 1; i < 11; i++) {
    qtyButtons.push(<div
        onClick={(btn) => {qtyBtnToggle(btn);setMqty(i); }}
    >
      {i}
    </div>)
  }

Thank you in advance.



Solution 1:[1]

I think using a map function is the correct way for doing it.

Therefore, you must generate a range of numbers our any element to be able to perform a map function.

So if i was in your place i would have do it like:

const [mqty, setMqty] = useState(0);

// ...

const qtyButtons = Array(10).fill().map((_, i) => {
  const value = parseInt(i);

  return (
    <button onClick={handleClick(value)}>
      {value}
    </button>
  );
});

// ...
// The trick here is that function returning another function, beware of that
const handleClick = (i) => () => {
  setMqty(i);
};

Solution 2:[2]

I am guessing setMqty is a state.Can you try

setMqty(currentValue=> currentValue+1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 pranit