Extended DateRangeSelector to allow updating its value via props after rendering

This commit is contained in:
Alejandro Celaya 2021-12-22 20:14:26 +01:00
parent 7adb40489d
commit 401418c049
2 changed files with 12 additions and 2 deletions

View file

@ -1,6 +1,7 @@
import { useState } from 'react';
import { DropdownItem } from 'reactstrap';
import { DropdownBtn } from '../DropdownBtn';
import { useEffectExceptFirstTime } from '../helpers/hooks';
import {
DateInterval,
DateRange,
@ -17,10 +18,11 @@ export interface DateRangeSelectorProps {
disabled?: boolean;
onDatesChange: (dateRange: DateRange) => void;
defaultText: string;
updatable?: boolean;
}
export const DateRangeSelector = (
{ onDatesChange, initialDateRange, defaultText, disabled }: DateRangeSelectorProps,
{ onDatesChange, initialDateRange, defaultText, disabled, updatable = false }: DateRangeSelectorProps,
) => {
const initialIntervalIsRange = rangeIsInterval(initialDateRange);
const [ activeInterval, setActiveInterval ] = useState(initialIntervalIsRange ? initialDateRange : undefined);
@ -37,6 +39,14 @@ export const DateRangeSelector = (
onDatesChange(intervalToDateRange(dateInterval));
};
updatable && useEffectExceptFirstTime(() => {
if (rangeIsInterval(initialDateRange)) {
updateInterval(initialDateRange);
} else if (initialDateRange) {
updateDateRange(initialDateRange);
}
}, [ initialDateRange ]);
return (
<DropdownBtn disabled={disabled} text={rangeOrIntervalToString(activeInterval ?? activeDateRange) ?? defaultText}>
<DateIntervalDropdownItems allText={defaultText} active={activeInterval} onChange={updateInterval} />

View file

@ -44,7 +44,7 @@ describe('<DateRangeSelector />', () => {
[ 'last7Days' as DateInterval, 1 ],
[ 'last30Days' as DateInterval, 1 ],
[ 'last90Days' as DateInterval, 1 ],
[ 'last180days' as DateInterval, 1 ],
[ 'last180Days' as DateInterval, 1 ],
[ 'last365Days' as DateInterval, 1 ],
[{ startDate: new Date() }, 0 ],
])('sets proper element as active based on provided date range', (initialDateRange, expectedActiveIntervalItems) => {