diff --git a/.changeset/few-dragons-behave.md b/.changeset/few-dragons-behave.md new file mode 100644 index 0000000000..093d0e05c6 --- /dev/null +++ b/.changeset/few-dragons-behave.md @@ -0,0 +1,5 @@ +--- +"@navikt/ds-react": patch +--- + +Datepicker: Use of 'open'-prop set to 'true' on first render could lead to the dialog not opening. diff --git a/@navikt/core/react/src/date/datepicker/DatePicker.tsx b/@navikt/core/react/src/date/datepicker/DatePicker.tsx index 53f2f96d0a..64b9f65d33 100644 --- a/@navikt/core/react/src/date/datepicker/DatePicker.tsx +++ b/@navikt/core/react/src/date/datepicker/DatePicker.tsx @@ -1,6 +1,6 @@ import cl from "clsx"; import { isWeekend } from "date-fns"; -import React, { forwardRef, useRef, useState } from "react"; +import React, { forwardRef, useState } from "react"; import { DateRange, DayPicker, isMatch } from "react-day-picker"; import { omit } from "../../util"; import { useId } from "../../util/hooks"; @@ -88,8 +88,9 @@ export const DatePicker = forwardRef( const ariaId = useId(id); const [open, setOpen] = useState(_open ?? false); - const wrapperRef = useRef(null); - const mergedRef = useMergeRefs(wrapperRef, ref); + /* We use state here to insure that anchor is defined if open is true on initial render */ + const [wrapperRef, setWrapperRef] = useState(null); + const mergedRef = useMergeRefs(setWrapperRef, ref); const [selectedDates, setSelectedDates] = React.useState< Date | Date[] | DateRange | undefined @@ -167,7 +168,7 @@ export const DatePicker = forwardRef( {children} onClose?.() ?? setOpen(false)} locale={locale} variant={mode} diff --git a/@navikt/core/react/src/date/monthpicker/MonthPicker.tsx b/@navikt/core/react/src/date/monthpicker/MonthPicker.tsx index 649dfe205c..3a3f91d0d5 100644 --- a/@navikt/core/react/src/date/monthpicker/MonthPicker.tsx +++ b/@navikt/core/react/src/date/monthpicker/MonthPicker.tsx @@ -1,5 +1,5 @@ import cl from "clsx"; -import React, { forwardRef, useRef, useState } from "react"; +import React, { forwardRef, useState } from "react"; import { DayPickerProvider } from "react-day-picker"; import { useId } from "../../util/hooks"; import { useMergeRefs } from "../../util/hooks/useMergeRefs"; @@ -81,8 +81,9 @@ export const MonthPicker = forwardRef( const ariaId = useId(id); const [open, setOpen] = useState(_open ?? false); - const wrapperRef = useRef(null); - const mergedRef = useMergeRefs(wrapperRef, ref); + /* We use state here to insure that anchor is defined if open is true on initial render */ + const [wrapperRef, setWrapperRef] = useState(null); + const mergedRef = useMergeRefs(setWrapperRef, ref); const [selectedMonth, setSelectedMonth] = useState( defaultSelected, @@ -118,7 +119,7 @@ export const MonthPicker = forwardRef( {children} onClose?.() ?? setOpen(false)} locale={locale} variant="month"