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

1

1 Answer 1

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> 
     )
   }
</>)
Sign up to request clarification or add additional context in comments.

4 Comments

Hey, this doesn't seem to loop at all. I think it must be close though. Thanks
Still nothing unfortunately
Sorry had another look and turns out it doesn't work with the () brackets after the =>. I removed the (brackets) around the div and it works. Thanks!
Oh... It was the semi-colon there :) Ive removed it now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.