Search code examples
reactjsreact-datepicker

How to highlight React date picker days based on the Api response


I have an api that returns the Unix time stamps of more than 50 days in a UseState variable.

 const [alldata, setData] = useState(null); 

 useEffect(() => {
    fetch(`/getdates}`)
     .then((response) => response.json())
     .then((actualData) => setData(actualData));
     }, []);

I want to highlight all this dates in the react date picker.

      <DatePicker 
        dateFormat="dd/MM/yyyy h:mm aa"
        selected={startDate}
        onChange={(date) => {setStartDate(date)}}
        highlightDates={[new Date("2023-08-31")]}
                            // how to add all the dates here
        
         />

I tried to do a map function inside, but its throwing errors. what the best way to tackle this? Thanks !


Solution

  • Can refer to below snippet and see if it helps. Here the allData array has the dates in epoch format and while passing the dates as prop to the DatePicker component I am destructuring the array and at the same time converting the epoch dates to a JS Date object.

    Depending on the result of your rest API you can modify the map function.

    import React, { useState, useEffect } from "react";
    import DatePicker from "react-datepicker";
    import "react-datepicker/dist/react-datepicker.css";
    export default function App() {
      
      const [startDate, setStartDate] = useState(new Date());
      const [allData, setData] = useState(null); 
    
     useEffect(() => {
        setData([1693460210000,1693373810000,1693287410000]);
         }, []);
    
      return (
        
            <DatePicker
              selected={startDate}
              onChange={(date) => setStartDate(date)}
              highlightDates={allData?.length ?  [...allData.map(d=>new Date(d))] :[]}
              placeholderText="This highlights a week ago and a week from today"
            />
      )
    }