0

I want to highlight the next two weeks from the current date. I am using react-datepicker module. I used the below code:

var currentDate = new Date();
var numberOfDaysToAdd = 13;
const daysHighlighted = new Array(numberOfDaysToAdd).fill(currentDate);

return (
    <DatePicker
        selected={this.state.startDate}
        onChange={this.handleChange}
        highlightDates={[{
            "react-datepicker__day--highlighted": daysHighlighted.map((day, index) => {
                day.setDate(day.getDate() + index)
                return new Date(day)
            })
        }]}
    />
)

Which is giving me the unexpected result.

I just want to highlight next two weeks including current Date.

mehamasum
  • 5,554
  • 2
  • 21
  • 30
Rajat
  • 486
  • 1
  • 10
  • 35

1 Answers1

0

fill function fills the Array with same Date instance. So whenever you are updating a date with setDate, it changes the value of other dates of that array. Because they all point to the same object.

You can try something like this:

new Array(numberOfDaysToAdd).fill().map((_, i) => {   // fills the array with `undefined`
  const d = new Date();                               // create a new Date instance
  d.setDate(d.getDate() + i);                         // update only that instance
  return d;                                           // return the updated date
})

Now you can use this array as the value of react-datepicker__day--highlighted key:

<DatePicker
    selected={this.state.startDate}
    onChange={this.handleChange}
    highlightDates={[{
        "react-datepicker__day--highlighted": new Array(numberOfDaysToAdd).fill().map((_, i) => {  
          const d = new Date();
          d.setDate(d.getDate() + i);
          return d;
      })
    }]}
/>
mehamasum
  • 5,554
  • 2
  • 21
  • 30