reactjsreact-day-picker

React Date-picker Selecting a Range of days not working


I would like to show a specific range of selected Dates from React Date-Picker. I have tried with their documentation site demo code. but this code is not working .what will be the solution? Below is my sample code, `

import React, { useState } from 'react';
import { addDays, format } from 'date-fns';
import { DateRange, DayPicker } from 'react-day-picker';

const pastMonth = new Date();
const App = () => {
  const defaultSelected: DateRange = {
    from: pastMonth,
    to: addDays(pastMonth, 4)
  };
  const [range, setRange] = useState < DateRange | undefined > (defaultSelected);
  let footer = <p>Please pick the first day.</p>;
  if (range?.from) {
    if (!range.to) {
      footer = <p>{format(range.from, 'PPP')}</p>;
    } else if (range.to) {
      footer = (
        <p>
          {format(range.from, 'PPP')}–{format(range.to, 'PPP')}
        </p>
      );
    }
  }
  return (
    <div>
      <DayPicker
        mode="range"
        defaultMonth={pastMonth}
        selected={range}
        footer={footer}
        onSelect={setRange}
      />
    </div>
  );
};

export default App;

`

I have tried to react day picker documentation site Selecting a Range of days demo code and I would like to show and selete range of date based on react: 18.2.0


Solution

  • I remove all types from prev code for use as js code. try this:

    import React, { useState } from 'react';
    import { addDays, format } from 'date-fns';
    import {  DayPicker } from 'react-day-picker';
    
    const pastMonth = new Date();
    const App = () => {
      const defaultSelected = {
        from: pastMonth,
        to: addDays(pastMonth, 4)
      };
      const [range, setRange] = useState(defaultSelected);
      let footer = <p>Please pick the first day.</p>;
      if (range?.from) {
        if (!range.to) {
          footer = <p>{format(range.from, 'PPP')}</p>;
        } else if (range.to) {
          footer = (
            <p>
              {format(range.from, 'PPP')}–{format(range.to, 'PPP')}
            </p>
          );
        }
      }
      return (
        <div>
          <DayPicker
            mode="range"
            defaultMonth={pastMonth}
            selected={range}
            footer={footer}
            onSelect={setRange}
          />
        </div>
      );
    };
    
    export default App;