Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can we not have initial selection in DateRange? #330

Open
rajubushanam opened this issue Dec 9, 2019 · 42 comments
Open

How can we not have initial selection in DateRange? #330

rajubushanam opened this issue Dec 9, 2019 · 42 comments

Comments

@rajubushanam
Copy link

I am trying to use a DateRange component and I would like to have my initial Calendar empty with nothing selected. Once I start clicking on the calendar then I expect the onChange event to be triggered so we can select the ranges.
Looks like if I pass dateRange: {startDate: null, endDate: null} it comes up with no selection, but if I click on the calendar, onChange event is not being called. Am I doing something wrong here?
Any help would be appreciated.
Thanks.

@onurkerimov
Copy link
Contributor

I think in your case, you should also set a key named 'key' to your selection:

import { useState } from 'react';

const [state, setState] = useState([
  {
    startDate: null,
    endDate: null,
    key: 'selectionName'
  }
]);

<DateRangePicker
  onChange={item => setState([item.selectionName])}
  showSelectionPreview={true}
  moveRangeOnFirstSelection={false}
  ranges={state}
  direction="horizontal"
/>;

@tristramjones
Copy link

I'm curious about this as well. I only have 1 range and am setting the initial state of startDate and endDate to null while setting a key. I would expect the calendar to initially render with no selection. The initial render shows the current month's dates highlighted as if selected even though startDate and endDate are set to null.

https://codesandbox.io/s/react-date-range-demo-s1tik

@gaieges
Copy link

gaieges commented Nov 4, 2020

I've got the same problem, seems as though there's no way to have an empty selection. You either have:

an empty array in the initial state: throws an exception:

Cannot read property 'color' of undefined
DateRange.eval [as updatePreview]
https://4y5g3.csb.app/node_modules/react-date-range/dist/components/DateRange/index.js:182:43
onPreviewChange
https://4y5g3.csb.app/node_modules/react-date-range/dist/components/DateRange/index.js:209:18

the null suggestion above which results in the entire month being selected:

Screen Shot 2020-11-03 at 8 52 32 PM

@Veda-cmd
Copy link

I found a solution. Do not just pass null. Pass it as new Date(null).
startDate: new Date(null),
endDate: new Date(null).

image

@gaieges
Copy link

gaieges commented Nov 20, 2020

Very cool, but defaults to Jan 1 1970.

I ended up hacking around this by using:

            startDate: new Date(),
            endDate: addDays(new Date(), 1),

@evorgevol
Copy link

I too am looking to not have an initial value for the DateRange picker. Can we re-open this issue as it's currently not resolved?

@Wgil
Copy link

Wgil commented Jan 4, 2021

I'm also facing this issue.

@jasonharrison
Copy link

There is currently no way to not have an initial value for the DateRange picker. This issue should not have been closed.

@icelic
Copy link

icelic commented Jan 11, 2021

I found a workaround. If you have multiple ranges in your initial state object just leave out the range which you do not want to define in the calendar.

Instead of:

const [ranges, setRanges] = useState({
    selection: {
      startDate: new Date(),
      endDate: subDays(new Date(), 7),
      key: 'selection',
    },
    compare: {
      startDate: new Date(),
      endDate: subDays(new Date(), 7),
      key: 'compare',
    },
  });

Leave out compare:

const [ranges, setRanges] = useState({
    selection: {
      startDate: new Date(),
      endDate: subDays(new Date(), 7),
      key: 'selection',
    },
  });

And then in the onChange handler add the missing range in the state object and it should appear on the calendar.

Note: I am using custom date display inputs instead of default ones, so I am not sure if this will work but maybe the idea will help.

@gaieges
Copy link

gaieges commented Jan 11, 2021

ranges expects an array, are you using that ranges var directly in the DatePicker?

I played around with the codesandbox in the comment above and couldn't get it to work that way. Curious if you would have any luck with that approach there @icelic ?

@icelic
Copy link

icelic commented Jan 12, 2021

I had multiple ranges and I wanted the second one not to be selected by default, but I am not sure if that can be applied to this case/sandobx.

@Victor-Varghese
Copy link

any new updates? i'm also facing same issue @onurkerimov

how to show picker without a range selected? set start/end as null, its selecting all days

@fmarcoccia
Copy link

Any update for this issue?

@ahmedrafayat
Copy link

This shouldn't require "hacking" for a solution. Should be fixed asap

@aaron5670
Copy link

Any update for this issue?

@davisraimon
Copy link

Hey guys...Try this

startDate : null
endDate : new Date("")
key : 'selection'

@fmarcoccia
Copy link

fmarcoccia commented Mar 19, 2021

Hey guys...Try this

startDate : null
endDate : new Date("")
key : 'selection'

It works, but this is a workaround, maybe the date range should have an empty state

@davisraimon
Copy link

Hey guys...Try this

startDate : null
endDate : new Date("")
key : 'selection'

It works, but this is a workaround, maybe the date range should have an empty state

Yes ofc....it should support that.

@maks-plotnikoff
Copy link

maks-plotnikoff commented Apr 8, 2021

why is it closed? The problem is still not resolved

@onurkerimov onurkerimov reopened this Apr 11, 2021
@bstrihova
Copy link

hi, are there any plans to solve this anytime soon?

@strangeweb3guy
Copy link

It should be the default non-selected state. Any updates?

@russellr922
Copy link

Same problem here

@hugo-licon
Copy link

I have the same issue

@hugo-licon
Copy link

I found a "fix" for this, but I updated the source code to accomplish this and I don't know if it can affect the functionality of other components:
chrome-capture

I just set the startDate and the endDate to null and to avoid errors with that, on the DayCell component I added this condition:

const inRanges = ranges.reduce((result, range) => { 
  let startDate = range.startDate;
  let endDate = range.endDate;
+ if (!startDate || !endDate) return result;
  if (startDate && endDate && isBefore(endDate, startDate)) {
      [startDate, endDate] = [endDate, startDate];
  }  
  startDate = startDate ? endOfDay(startDate) : null;
  endDate = endDate ? startOfDay(endDate) : null;
  const isInRange =
        (!startDate || isAfter(day, startDate)) && (!endDate || isBefore(day, endDate));
  const isStartEdge = !isInRange && isSameDay(day, startDate);
  const isEndEdge = !isInRange && isSameDay(day, endDate);
  if (isInRange || isStartEdge || isEndEdge) {
    return [
      ...result,
      {
            isStartEdge,
            isEndEdge: isEndEdge,
            isInRange,
            ...range,
          },
      ];
   }
  return result;
}, []);

@atefBB
Copy link
Contributor

atefBB commented Nov 8, 2021

@hugo-licon I do what you've mentioned but without success ! Any ideas to solve this? Thx !

@ihtisham1211
Copy link

Any fixes for this ?

@lConstantine
Copy link

the problem is still live and kicking

@kkallasm
Copy link

Any updates?

@osvaldo-dias-kununu
Copy link

Any updates about that?

@povilasbaranovas
Copy link

+1 on this one. Currently had to resort to setting the endDate to be invalid as @davisraimon has suggested, but i really do not like this workaround. :/

@artursOs
Copy link

+1 here

@kdoda
Copy link

kdoda commented Jul 7, 2022

Any update on this issue?

@atefBB
Copy link
Contributor

atefBB commented Jul 10, 2022

Any update on this issue?

Hey @kdoda! I made my own fork to fix this issue see the link it may help you. I have a PR opened about this #530.

@subashrimal01
Copy link

+1 here

2 similar comments
@yurdigrfnn
Copy link

+1 here

@marta-256
Copy link

+1 here

@avijit-devdynamics
Copy link

avijit-devdynamics commented Aug 3, 2023

Can anyone solve this issue. same problem.

@R4hman
Copy link

R4hman commented Jan 14, 2024

+1

@iddk0321
Copy link

iddk0321 commented Feb 1, 2024

I initially set up the calendar with the following initial values and left it blank.

startDate: null
endDate: new Date("")
key: 'selection'

After selecting a range and then resetting it to the initial values to clear the selected range, I found that the month displayed on the calendar behaves strangely.
If you are experiencing the same issue, I recommend changing the endDate to new Date(1).

startDate: null
endDate: new Date(1)
key: 'selection'

@hagealex
Copy link

+1 here

@Frankusky
Copy link

+1

Also, worth to mention that setting null to startDate/endDate will throw a typescript error as Range interface states that it should be Date|undefined
imagen

@fazlyalahi01
Copy link

fazlyalahi01 commented Jul 29, 2024

I ended up with something like this>>

"use client"

import { Box, Button, Grid, InputAdornment } from "@mui/material";
import { CalendarIcon } from "@mui/x-date-pickers";
import moment from "moment";
import React from "react";
import { DateRangePicker } from 'react-date-range';
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css';
import CustomFormLabel from "./CustomFormLabel";
import CustomTextField from "./CustomTextField";
import "./custom-form-styles.css"
import { getCalenderId } from "utils/__api__/dashboard/get-calender";
import { produce } from "immer";

interface Props {
    setLoading: (value: boolean) => void;
    setFieldValue: (label: string, value: string[]) => void;
}

export default function CustomDateRangePicker({ setLoading, setFieldValue }: Props) {
    const [open, setOpen] = React.useState(false);
    const [dateUuids, setDateUuids] = React.useState<string[]>([])
    const [date, setDate] = React.useState({
        startDate: null,
        endDate: new Date(""),
        key: 'selection'
    })

    const handleDateChange = (ranges) => {
        setDate(ranges.selection)
    }

    console.log(dateUuids)

    const closeDate = async () => {
        setOpen(false);
        setLoading(true);
        try {
            const dateList = await getCalenderId(moment(date.startDate).format("YYYY-MM-DD"), moment(date.endDate).format("YYYY-MM-DD"));
            if (dateList.length > 0) {
                const newDateUuids = dateList.map((date) => date.calendar_uuid);
                setDateUuids([...newDateUuids]);
                setFieldValue("calendar_uuid_range", dateUuids)
            }
        } catch (error) {
            console.log(error)
        } finally {
            setLoading(false)
        }
    }

    return (
        <>
            <Grid container spacing={2}>
                <Grid item xs={12} sm={6}>
                    <CustomTextField
                        value={date.startDate ? moment(date.startDate).format('DD MMMM dddd') : ""}
                        fullWidth
                        placeholder="Checkin"
                        InputProps={{
                            endAdornment: (
                                <InputAdornment position="end">
                                    <CalendarIcon />
                                </InputAdornment>
                            )
                        }}
                        onClick={() => (setOpen((pre) => !pre))}
                        sx={{ cursor: "pointer" }}
                    />
                </Grid>
                <Grid item xs={12} sm={6} >
                    <CustomTextField
                        value={isNaN(date.endDate.getTime()) ? null : moment(date.endDate).format('DD MMMM dddd')}
                        fullWidth
                        placeholder="Checkout"
                        InputProps={{
                            endAdornment: (
                                <InputAdornment position="end">
                                    <CalendarIcon />
                                </InputAdornment>
                            )
                        }}
                        onClick={() => (setOpen((pre) => !pre))}
                        sx={{ cursor: "pointer" }}
                    />

                </Grid>

            </Grid>
            {
                open && (
                    <Box>
                        <DateRangePicker
                            ranges={[date]}
                            onChange={handleDateChange}
                            minDate={new Date()}
                            maxDate={moment().add(2, "month").toDate()}
                            months={2}
                            direction="horizontal"
                            showDateDisplay={false}
                            staticRanges={[]}
                            inputRanges={[]}
                            zIndex={200}
                            shownDate={new Date()}
                        />
                        <Button
                            variant="contained"
                            onClick={closeDate}
                            color="info"
                        >
                            Apply
                        </Button>
                    </Box>
                )
            }
        </>
    );
}

Output:
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests