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.
CodePudding user response:
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.
CodePudding user response:
You have to pass a reference to a function, not call it:
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()
CodePudding user response:
you don't have to call the function directly. do something like this
const btn = <button onClick={() => clickHandler(i)}>{i}</button>