Home > front end >  ReactJS for loop create buttons and set variable according to the integer in the loop
ReactJS for loop create buttons and set variable according to the integer in the loop

Time:02-23

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.

CodePudding user response:

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);
};

CodePudding user response:

I am guessing setMqty is a state.Can you try

setMqty(currentValue=> currentValue 1)
  • Related