Reputation: 5061
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
Upvotes: 0
Views: 45
Reputation: 2187
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>
)
}
</>)
Upvotes: 2