-2

In the following code handlePage always report 30 instead of the index i. This is not strictly ReactJS related but general JS behavior. What is causing this and how do I fix it?

  const handlePage = (x) => {
    console.log(x)
  }

  return (
     for(var i = 0; i<30; i++) {
         <div onClick={() => handlePage(i)}>{i}</div> 
     }
  )
Fakeer
  • 985
  • 1
  • 13
  • 29
  • Are you trying to ***map*** 30 `div` elements to your UI? Also, do you have a specific question or issue you want resolved? Your title and description read more like statements. – Drew Reese Nov 08 '20 at 23:34
  • You're right, that's nothing to do with React, so have you looked at e.g. https://stackoverflow.com/q/2663594/3001761? – jonrsharpe Nov 08 '20 at 23:34

1 Answers1

1

because when you click the loop is over and i = 30 :)

You can fix the behavior with this small modification :

const handlePage = (x) => {
  console.log(x)
}

return (
  for(let i = 0; i<30; i++) {
    <div onClick={() => handlePage(i)}>{i}</div> 
  }
)

Using 'let' keyword, it makes 'i' scoped to the content of the loop, allowing each iterations in the loop to use a new value :)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

Ji aSH
  • 3,206
  • 1
  • 10
  • 18