Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function being called while generating buttons with onClick property (React)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading