-1

What is this method of pushing components to an array?

days.push(

        <Day day={day}
          selected={selected}
          select={select}/>
      );

I read this code but couldn't understand few things in it.

class Week extends React.Component {
  render() {
    let days = [];
    let {date,} = this.props;
    const { month,selected,select, } = this.props;
    console.log(`Inside weeks ${month.toString()}`);
    console.log(`Selected weeks ${selected.toString()}`);


    for (var i = 0; i < 7; i++) {

      let day = {
          name: date.format("dd").substring(0, 1),
          number: date.date(),
          isCurrentMonth: date.month() === month.month(),
          isToday: date.isSame(new Date(), "day"),
          date: date
      };



      days.push(

        <Day day={day}
          selected={selected}
          select={select}/>
      );
      console.log(`days inside return is ${days.selected}`);
      date = date.clone();
      date.add(1, "day");
    }


    return (

      <div className="row week" key={days[0]}>
        {days}
      </div>
    );
  }

}

I am quite puzzled at this step in code where apart from passing properties to another class ,it has also been pushed to an array and later same has been returned

<div className="row week" key={days[0]}>
        {days}
      </div>
iamredpanda
  • 113
  • 3
  • 11
  • props is not pushed into an array, components (React Elements) are. you should learn more about react – Rei Dien Mar 01 '18 at 08:43
  • @ReiDien Can you just explain the above process or link me to something to read ? – iamredpanda Mar 01 '18 at 08:48
  • first, in react you can display a variable. `
    {variable}
    `. basically it just creates an array of React Elements and then renders it. thats all no fancy stuff.
    – Rei Dien Mar 01 '18 at 08:48

1 Answers1

0

This is a way to dynamically render element inside a loop. you render them and push them inside an array and then render the array (as the array is built of react elements, it will just render). Have a look here: Loop inside React JSX

Matan Bobi
  • 2,693
  • 1
  • 15
  • 27