I’m trying to create a calculator, So I have to add buttons for number 1 to 9. And I’m trying to do it in the most "programming" way by creating a function that would generate all of the buttons instead of creating it one by one.
const getNumbers = () => {
let buttons = []
for (let i=1; i<10; i++){
const btn = <button onClick={clickHandler(i)}>{i}</button>
buttons.push(btn)
}
return buttons
}
const numbers = getNumbers()
However, when I display it (numbers), the clickHandler function is being called everytime the button is generated.
>Solution :
This should do the work for you.
...
const btn = <button onClick={() => clickHandler(i)}>{i}</button>
...
Otherwise, every time the button got created, the onClick function will fire automatically.
You can read more about when to bind a direct function or the arrow function to the element or component in the react docs.