0

Can someone explain why this loop when rendered and clicked on always sends the one same value to my function

class AppointmentSelect extends React.Component {

changeDate = x => {
    console.log(x);
}

render () {

    let daysArray=[];
    for (var i = 0; i < 7; i++) { 
      daysArray.push( 
        <div className="day" onClick={() => this.changeDate(startDate+i) }>
          <h1>Mo</h1>
          <p>{ startDate + i }</p>
        </div> 
      );
    }
    return <>{ daysArray }</>

}}

changeDate always sends the i as a 7 so it renders as

Mo 1 Mo 2 Mo 3 Mo 4 Mo 5 Mo 6 Mo 7

But clicking any number sends the value "7"

How can I get this to work? Thanks

MomasVII
  • 4,641
  • 5
  • 35
  • 52
  • Does this answer your question? [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – CertainPerformance Oct 22 '20 at 22:07

1 Answers1

2

This is not the correct way to render a list in React. Almost always, you'll want to map over an array instead - This should work:

return (<>
   {
     new Array(7).fill().map((_, index) => ( 
        <div className="day" onClick={() => this.changeDate(startDate+index) }>
          <h1>Mo</h1>
          <p>{ startDate + index }</p>
        </div> 
     )
   }
</>)
Dylan Kerler
  • 2,007
  • 1
  • 8
  • 23