Search code examples
javascriptreactjsreact-day-picker

How to pass an array of dates to selectedDays in react-day-picker?


I have a Calendar component that uses react-day-picker to display a Calendar as so:

const Calendar = ({dateItems}) => {

    const [selectedDay, setSelectedDay] = useState(null)

    function handleDayClick(day) {
        setSelectedDay(day)
    }

    return (
        <DayPicker
           initialMonth={new Date(2021, 2)}
           onDayClick={handleDayClick}
           numberOfMonths={2}
           selectedDays={[
                new Date(dateItems[0]),
                new Date(dateItems[1]),
                new Date(dateItems[2]),
                new Date(dateItems[3]),
                new Date(dateItems[4]),
                new Date(dateItems[5]),
           ]}
       />
    );
}

The component is passed the 'dateItems' array of dates, and I would like to be able to render this array of dates. At the moment, and for the sake of this example, I am stipulating the first six entries in the array manually [0,1,2,3 etc..].

Is this possible, and what would be the best way of doing it, please?

Cheers, Matt


Solution

  • Like this:

    <DayPicker
        ...
        selectedDays={dateItems.map(date => new Date(date))}
    />
    

    Thanks to react-day-picker's author for this.