Reputation: 59
I am trying to add a custom calender header for the MUI Date Picker component but am running into troubles when changing the default dayjs type to date-fns.
Here is my Date Picker component and custom header component.
<StyledDatePicker
open={open}
value={date}
onChange={(newValue) => onChange(newValue as Date)}
slots={{
openPickerIcon: CalendarIcon,
shortcuts: CustomRangeShortcuts as any,
calendarHeader: CustomCalendarHeader,
}}
slotProps={{
actionBar: {
actions: ['today'],
},
shortcuts: {
items: MUI_DATE_PICKER_SHORTCUTS,
},
openPickerButton: {
onClick: iconButtonOnClick,
},
textField: { variant: 'filled', onFocus: inputFocused, onBlur: close },
}}
/>
const CustomCalendarHeader = (props: PickersCalendarHeaderProps<Date>) => {
const { currentMonth, onMonthChange } = props;
const selectNextMonth = () => onMonthChange(currentMonth.add(1, 'month'), 'left');
const selectNextYear = () => onMonthChange(currentMonth.add(1, 'year'), 'left');
const selectPreviousMonth = () => onMonthChange(currentMonth.subtract(1, 'month'), 'right');
const selectPreviousYear = () => onMonthChange(currentMonth.subtract(1, 'year'), 'right');
return (
<CustomCalendarHeaderRoot>
<Stack spacing={1} direction="row">
<IconButton onClick={selectPreviousYear} title="Previous year">
<KeyboardDoubleArrowLeftIcon />
</IconButton>
<IconButton onClick={selectPreviousMonth} title="Previous month">
<ChevronLeft />
</IconButton>
</Stack>
<Typography variant="body2">{currentMonth.format('MMMM YYYY')}</Typography>
<Stack spacing={1} direction="row">
<IconButton onClick={selectNextMonth} title="Next month">
<ChevronRight />
</IconButton>
<IconButton onClick={selectNextYear} title="Next year">
<KeyboardDoubleArrowRightIcon />
</IconButton>
</Stack>
</CustomCalendarHeaderRoot>
);
}
The custom header prop type in the example uses Dayjs (PickersCalendarHeaderProps<Dayjs>
) but I want to use date-fns, how can I implement this using date-fns instead of dayjs?
Upvotes: 0
Views: 216
Reputation: 2899
The date-fns
provides similar functions as day.js
. Check the code below: 👇
import { addMonths, addYears, subMonths, subYears } from 'date-fns';
const selectNextMonth = () => onMonthChange(addMonths(currentMonth, 1), 'left');
const selectNextYear = () => onMonthChange(addYears(currentMonth, 1), 'left');
const selectPreviousMonth = () => onMonthChange(subMonths(currentMonth, 1), 'right');
const selectPreviousYear = () => onMonthChange(subYears(currentMonth, 1), 'right');
These changes will work the same as what you were doing with day.js
.
Upvotes: 0