단축키
단축키 (Shortcuts)
날짜 선택기에 커스텀 단축키를 추가할 수 있어요.
본문
단축키 추가하기 (Adding shortcuts)
기본적으로 피커는 PickersShortcuts 컴포넌트를 사용해 단축키를 표시합니다. 이 컴포넌트는 shortcuts prop으로 PickersShortcutsItem 배열을 받아요. 이 항목들은 두 개의 필수 속성으로 이루어집니다.
label: 단축키 칩에 표시되는 문자열. 이 속성은 고유해야 합니다.getValue: 단축키와 연결된 값을 반환하는 함수.
slotProps.shortcuts를 사용해 이 prop을 커스터마이즈할 수 있어요. 예를 들어 크리스마스 단축키를 추가하려면 다음과 같이 합니다.
<DatePicker
slotProps={{
shortcuts: {
items: [
{
label: 'Christmas',
getValue: () => {
return dayjs(new Date(2023, 11, 25));
},
},
],
},
}}
/>
import dayjs, { Dayjs } from 'dayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { StaticDatePicker } from '@mui/x-date-pickers/StaticDatePicker';
import { PickersShortcutsItem } from '@mui/x-date-pickers/PickersShortcuts';
const getMonthWeekday = (
monthIndex: number,
weekdayIndex: number,
dayRank: number,
) => {
// Helper to find the nth weekday in a given month.
// For example, Find the 3rd Monday in January.
const today = dayjs();
const firstDayOfMonth = today.month(monthIndex).startOf('month');
const weekDay = firstDayOfMonth.day(); // 0 (Sunday) to 6 (Saturday)
const deltaToFirstValidWeekDayInMonth =
(weekDay > weekdayIndex ? 7 : 0) + weekdayIndex - weekDay;
return firstDayOfMonth.add(
(dayRank - 1) * 7 + deltaToFirstValidWeekDayInMonth,
'day',
);
};
const shortcutsItems: PickersShortcutsItem<Dayjs | null>[] = [
{
label: "New Year's Day",
getValue: () => {
// (January 1)
const today = dayjs();
return today.month(0).date(1);
},
},
{
label: 'Birthday of MLK Jr.',
getValue: () => {
// (third Monday in January)
return getMonthWeekday(0, 1, 3);
},
},
{
label: 'Independence Day',
getValue: () => {
// (July 4)
const today = dayjs();
return today.month(6).date(4);
},
},
{
label: 'Labor Day',
getValue: () => {
// (first Monday in September)
return getMonthWeekday(8, 1, 1);
},
},
{
label: 'Thanksgiving Day',
getValue: () => {
// (fourth Thursday in November)
return getMonthWeekday(10, 4, 4);
},
},
{
label: 'Christmas Day',
getValue: () => {
// (December 25)
const today = dayjs();
return today.month(11).date(25);
},
},
];
export default function BasicShortcuts() {
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<StaticDatePicker
slotProps={{
shortcuts: {
items: shortcutsItems,
},
}}
/>
</LocalizationProvider>
);
}
비활성화된 날짜 (Disabled dates)
기본적으로 반환된 값이 검증을 통과하지 못하면 단축키는 비활성화됩니다. 여기 예시에서는 minDate가 연중의 중간으로 설정됩니다.
import dayjs, { Dayjs } from 'dayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { StaticDatePicker } from '@mui/x-date-pickers/StaticDatePicker';
import { PickersShortcutsItem } from '@mui/x-date-pickers/PickersShortcuts';
const getMonthWeekday = (
monthIndex: number,
weekdayIndex: number,
dayRank: number,
) => {
// Helper to find the nth weekday in a given month.
// For example, Find the 3rd Monday in January.
const today = dayjs();
const firstDayOfMonth = today.month(monthIndex).startOf('month');
const weekDay = firstDayOfMonth.day(); // 0 (Sunday) to 6 (Saturday)
const deltaToFirstValidWeekDayInMonth =
(weekDay > weekdayIndex ? 7 : 0) + weekdayIndex - weekDay;
return firstDayOfMonth.add(
(dayRank - 1) * 7 + deltaToFirstValidWeekDayInMonth,
'day',
);
};
const shortcutsItems: PickersShortcutsItem<Dayjs | null>[] = [
{
label: "New Year's Day",
getValue: () => {
// (January 1)
const today = dayjs();
return today.month(0).date(1);
},
},
{
label: 'Birthday of MLK Jr.',
getValue: () => {
// (third Monday in January)
return getMonthWeekday(0, 1, 3);
},
},
{
label: 'Independence Day',
getValue: () => {
// (July 4)
const today = dayjs();
return today.month(6).date(4);
},
},
{
label: 'Labor Day',
getValue: () => {
// (first Monday in September)
return getMonthWeekday(8, 1, 1);
},
},
{
label: 'Veterans Day',
getValue: () => {
// (November 11)
const today = dayjs();
return today.month(10).date(11);
},
},
{
label: 'Thanksgiving Day',
getValue: () => {
// (fourth Thursday in November)
return getMonthWeekday(10, 4, 4);
},
},
{
label: 'World AIDS Day',
getValue: () => {
// (December 1)
const today = dayjs();
return today.month(11).date(1);
},
},
{
label: 'Christmas Day',
getValue: () => {
// (December 25)
const today = dayjs();
return today.month(11).date(25);
},
},
];
export default function DisabledDatesShortcuts() {
const middleDate = dayjs(new Date().setMonth(6));
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<StaticDatePicker
slotProps={{
shortcuts: {
items: shortcutsItems,
},
}}
minDate={middleDate}
/>
</LocalizationProvider>
);
}
범위 단축키 (Range shortcuts)
범위 피커의 단축키는 getValue 속성이 두 값이 있는 배열을 반환해야 합니다.
import dayjs, { Dayjs } from 'dayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { StaticDateRangePicker } from '@mui/x-date-pickers-pro/StaticDateRangePicker';
import { PickersShortcutsItem } from '@mui/x-date-pickers/PickersShortcuts';
import { DateRange } from '@mui/x-date-pickers-pro/models';
const shortcutsItems: PickersShortcutsItem<DateRange<Dayjs>>[] = [
{
label: 'This Week',
getValue: () => {
const today = dayjs();
return [today.startOf('week'), today.endOf('week')];
},
},
{
label: 'Last Week',
getValue: () => {
const today = dayjs();
const prevWeek = today.subtract(7, 'day');
return [prevWeek.startOf('week'), prevWeek.endOf('week')];
},
},
{
label: 'Last 7 Days',
getValue: () => {
const today = dayjs();
return [today.subtract(7, 'day'), today];
},
},
{
label: 'Current Month',
getValue: () => {
const today = dayjs();
return [today.startOf('month'), today.endOf('month')];
},
},
{
label: 'Next Month',
getValue: () => {
const today = dayjs();
const startOfNextMonth = today.endOf('month').add(1, 'day');
return [startOfNextMonth, startOfNextMonth.endOf('month')];
},
},
{ label: 'Reset', getValue: () => [null, null] },
];
export default function BasicRangeShortcuts() {
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<StaticDateRangePicker
slotProps={{
shortcuts: {
items: shortcutsItems,
},
}}
/>
</LocalizationProvider>
);
}
고급 단축키 (Advanced shortcuts)
검증을 사용해 값 가져오기 (Use validation to get the value)
getValue() 메서드는 isValid() 헬퍼 함수를 받습니다. 이를 사용해 검증 props(validation props)를 기반으로 값이 유효한지 테스트할 수 있어요.
다음 데모에서는 이것을 사용해 다음 사용 가능한 주와 주말을 가져옵니다.
import dayjs, { Dayjs } from 'dayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { StaticDateRangePicker } from '@mui/x-date-pickers-pro/StaticDateRangePicker';
import { PickersShortcutsItem } from '@mui/x-date-pickers/PickersShortcuts';
import { DateRange } from '@mui/x-date-pickers-pro/models';
const shortcutsItems: PickersShortcutsItem<DateRange<Dayjs>>[] = [
{
label: 'Next Available Weekend',
getValue: ({ isValid }) => {
const today = dayjs();
const nextSaturday =
today.day() <= 6
? today.add(6 - today.day(), 'day')
: today.add(7 + 6 - today.day(), 'day');
let maxAttempts = 50;
let solution: [Dayjs, Dayjs] = [nextSaturday, nextSaturday.add(1, 'day')];
while (maxAttempts > 0 && !isValid(solution)) {
solution = [solution[0].add(7, 'day'), solution[1].add(7, 'day')];
maxAttempts -= 1;
}
return solution;
},
},
{
label: 'Next Available Week',
getValue: ({ isValid }) => {
const today = dayjs();
const nextMonday =
today.day() <= 1
? today.add(1 - today.day(), 'day')
: today.add(7 + 1 - today.day(), 'day');
let maxAttempts = 50;
let solution: [Dayjs, Dayjs] = [nextMonday, nextMonday.add(4, 'day')];
while (maxAttempts > 0 && !isValid(solution)) {
solution = [solution[0].add(7, 'day'), solution[1].add(7, 'day')];
maxAttempts -= 1;
}
return solution;
},
},
{ label: 'Reset', getValue: () => [null, null] },
];
const shouldDisableDate = (date: Dayjs) => {
const today = dayjs();
if (today.isSame(date, 'month')) {
return true;
}
const nextMonth = today.add(1, 'month').startOf('month');
if (date.isSame(nextMonth, 'month')) {
if (date.isSame(nextMonth, 'week')) {
return true;
}
return [10, 11, 12, 16, 18, 29, 30].includes(date.date());
}
return false;
};
export default function AdvancedRangeShortcuts() {
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<StaticDateRangePicker
shouldDisableDate={shouldDisableDate}
slotProps={{
shortcuts: {
items: shortcutsItems,
},
}}
/>
</LocalizationProvider>
);
}
어떤 단축키가 선택되었는지 알기 (Know which shortcut has been selected)
onChange 콜백은 단축키를 두 번째 인자의 속성으로 받습니다. 어떤 단축키가 선택되었는지 알아내는 데 사용할 수 있어요.
import * as React from 'react';
import dayjs, { Dayjs } from 'dayjs';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { StaticDatePicker } from '@mui/x-date-pickers/StaticDatePicker';
import {
PickersShortcutsItem,
PickersShortcutsItemContext,
} from '@mui/x-date-pickers/PickersShortcuts';
import {
DateValidationError,
PickerChangeHandlerContext,
} from '@mui/x-date-pickers/models';
const getMonthWeekday = (
monthIndex: number,
weekdayIndex: number,
dayRank: number,
) => {
// Helper to find for example the 3rd monday in Jun
const today = dayjs();
const firstDayOfMonth = today.month(monthIndex).startOf('month');
const weekDay = firstDayOfMonth.day(); // 0 (Sunday) to 6 (Saturday)
const deltaToFirstValidWeekDayInMonth =
(weekDay > weekdayIndex ? 7 : 0) + weekdayIndex - weekDay;
return firstDayOfMonth.add(
(dayRank - 1) * 7 + deltaToFirstValidWeekDayInMonth,
'day',
);
};
const shortcutsItems: PickersShortcutsItem<Dayjs | null>[] = [
{
label: "New Year's Day",
getValue: () => {
// (January 1)
const today = dayjs();
return today.month(0).date(1);
},
},
{
label: 'Birthday of MLK Jr.',
getValue: () => {
// (third Monday in January)
return getMonthWeekday(0, 1, 3);
},
},
{
label: 'Independence Day',
getValue: () => {
// (July 4)
const today = dayjs();
return today.month(6).date(4);
},
},
{
label: 'Labor Day',
getValue: () => {
// (first Monday in September)
return getMonthWeekday(8, 1, 1);
},
},
{
label: 'Thanksgiving Day',
getValue: () => {
// (fourth Thursday in November)
return getMonthWeekday(10, 4, 4);
},
},
{
label: 'Christmas Day',
getValue: () => {
// (December 25)
const today = dayjs();
return today.month(11).date(25);
},
},
];
export default function OnChangeShortcutLabel() {
const [value, setValue] = React.useState<Dayjs | null>(null);
const [lastShortcutSelected, setLastShortcutSelected] = React.useState<
PickersShortcutsItemContext | undefined
>(undefined);
const handleChange = (
newValue: Dayjs | null,
ctx: PickerChangeHandlerContext<DateValidationError>,
) => {
setValue(newValue);
setLastShortcutSelected(ctx.shortcut);
};
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<Stack spacing={2}>
<StaticDatePicker
value={value}
onChange={handleChange}
slotProps={{
shortcuts: {
items: shortcutsItems,
},
}}
/>
<Typography>
Selected shortcut on last onChange call:{' '}
{lastShortcutSelected === undefined ? 'none' : lastShortcutSelected.label}
</Typography>
</Stack>
</LocalizationProvider>
);
}
단축키를 선택했을 때의 동작 (Behavior when selecting a shortcut)
changeImportance 속성을 사용해 단축키를 선택했을 때의 동작을 바꿀 수 있어요.
"accept"(기본값):onChange를 실행하고,onAccept를 실행한 뒤 피커를 닫습니다."set":onChange는 실행하지만onAccept는 실행하지 않고 피커도 닫지 않습니다.
import * as React from 'react';
import dayjs, { Dayjs } from 'dayjs';
import Stack from '@mui/material/Stack';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { PickersShortcutsItem } from '@mui/x-date-pickers/PickersShortcuts';
import { PickerChangeImportance } from '@mui/x-date-pickers/models';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
const getMonthWeekday = (
monthIndex: number,
weekdayIndex: number,
dayRank: number,
) => {
// Helper to find the nth weekday in a given month.
// For example, Find the 3rd Monday in January.
const today = dayjs();
const firstDayOfMonth = today.month(monthIndex).startOf('month');
const weekDay = firstDayOfMonth.day(); // 0 (Sunday) to 6 (Saturday)
const deltaToFirstValidWeekDayInMonth =
(weekDay > weekdayIndex ? 7 : 0) + weekdayIndex - weekDay;
return firstDayOfMonth.add(
(dayRank - 1) * 7 + deltaToFirstValidWeekDayInMonth,
'day',
);
};
const shortcutsItems: PickersShortcutsItem<Dayjs | null>[] = [
{
label: "New Year's Day",
getValue: () => {
// (January 1)
const today = dayjs();
return today.month(0).date(1);
},
},
{
label: 'Birthday of MLK Jr.',
getValue: () => {
// (third Monday in January)
return getMonthWeekday(0, 1, 3);
},
},
{
label: 'Independence Day',
getValue: () => {
// (July 4)
const today = dayjs();
return today.month(6).date(4);
},
},
{
label: 'Labor Day',
getValue: () => {
// (first Monday in September)
return getMonthWeekday(8, 1, 1);
},
},
{
label: 'Thanksgiving Day',
getValue: () => {
// (fourth Thursday in November)
return getMonthWeekday(10, 4, 4);
},
},
{
label: 'Christmas Day',
getValue: () => {
// (December 25)
const today = dayjs();
return today.month(11).date(25);
},
},
];
export default function ChangeImportance() {
const [changeImportance, setChangeImportance] =
React.useState<PickerChangeImportance>('accept');
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<Stack spacing={3} sx={{ width: 300 }}>
<ToggleButtonGroup
value={changeImportance}
exclusive
fullWidth
onChange={(event, newEventImportance) => {
if (newEventImportance != null) {
setChangeImportance(newEventImportance);
}
}}
>
<ToggleButton value="accept">accept</ToggleButton>
<ToggleButton value="set">set</ToggleButton>
</ToggleButtonGroup>
<DatePicker
slotProps={{
shortcuts: {
items: shortcutsItems,
changeImportance,
},
}}
/>
</Stack>
</LocalizationProvider>
);
}
커스터마이즈 (Customization)
다른 레이아웃 하위 컴포넌트(layout subcomponents)처럼 단축키도 커스터마이즈할 수 있어요. 다음은 가로형 단축키의 예시입니다.
import dayjs, { Dayjs } from 'dayjs';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import Chip from '@mui/material/Chip';
import Divider from '@mui/material/Divider';
import Box from '@mui/material/Box';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { StaticDateRangePicker } from '@mui/x-date-pickers-pro/StaticDateRangePicker';
import {
PickersShortcutsItem,
PickersShortcutsProps,
} from '@mui/x-date-pickers/PickersShortcuts';
import { DateRange } from '@mui/x-date-pickers-pro/models';
import { useIsValidValue, usePickerContext } from '@mui/x-date-pickers/hooks';
const shortcutsItems: PickersShortcutsItem<DateRange<Dayjs>>[] = [
{
label: 'This Week',
getValue: () => {
const today = dayjs();
return [today.startOf('week'), today.endOf('week')];
},
},
{
label: 'Last Week',
getValue: () => {
const today = dayjs();
const prevWeek = today.subtract(7, 'day');
return [prevWeek.startOf('week'), prevWeek.endOf('week')];
},
},
{
label: 'Last 7 Days',
getValue: () => {
const today = dayjs();
return [today.subtract(7, 'day'), today];
},
},
{
label: 'Current Month',
getValue: () => {
const today = dayjs();
return [today.startOf('month'), today.endOf('month')];
},
},
{
label: 'Next Month',
getValue: () => {
const today = dayjs();
const startOfNextMonth = today.endOf('month').add(1, 'day');
return [startOfNextMonth, startOfNextMonth.endOf('month')];
},
},
{ label: 'Reset', getValue: () => [null, null] },
];
function CustomRangeShortcuts(props: PickersShortcutsProps<DateRange<Dayjs>>) {
const { items, changeImportance = 'accept' } = props;
const isValid = useIsValidValue<DateRange<Dayjs>>();
const { setValue } = usePickerContext<DateRange<Dayjs>>();
if (items == null || items.length === 0) {
return null;
}
const resolvedItems = items.map((item) => {
const newValue = item.getValue({ isValid });
return {
label: item.label,
onClick: () => {
setValue(newValue, { changeImportance, shortcut: item });
},
disabled: !isValid(newValue),
};
});
return (
<Box
sx={{
gridRow: 1,
gridColumn: 2,
}}
>
<List
dense
sx={(theme) => ({
display: 'flex',
px: theme.spacing(4),
'& .MuiListItem-root': {
pt: 0,
pl: 0,
pr: theme.spacing(1),
},
})}
>
{resolvedItems.map((item) => {
return (
<ListItem key={item.label}>
<Chip {...item} />
</ListItem>
);
})}
</List>
<Divider />
</Box>
);
}
export default function CustomizedRangeShortcuts() {
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<StaticDateRangePicker
slots={{
shortcuts: CustomRangeShortcuts,
}}
slotProps={{
shortcuts: {
items: shortcutsItems,
},
toolbar: {
hidden: true,
},
actionBar: {
hidden: true,
},
}}
calendars={2}
/>
</LocalizationProvider>
);
}
RTL 예시 (RTL example)
다른 커스터마이즈와 마찬가지로 단축키도 RTL 방향 설정을 따릅니다.
import * as React from 'react';
import dayjs, { Dayjs } from 'dayjs';
import { prefixer } from 'stylis';
import rtlPlugin from '@mui/stylis-plugin-rtl';
import createCache from '@emotion/cache';
import { CacheProvider } from '@emotion/react';
import { ThemeProvider, createTheme, useTheme } from '@mui/material/styles';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { StaticDatePicker } from '@mui/x-date-pickers/StaticDatePicker';
import { PickersShortcutsItem } from '@mui/x-date-pickers/PickersShortcuts';
import type {} from '@mui/x-date-pickers/themeAugmentation';
// Create rtl cache
const cacheRtl = createCache({
key: 'picker-shortcuts-rtl-demo',
stylisPlugins: [prefixer, rtlPlugin],
});
const getMonthWeekday = (
monthIndex: number,
weekdayIndex: number,
dayRank: number,
) => {
// Helper to find the nth weekday in a given month.
// For example, Find the 3rd Monday in January.
const today = dayjs();
const firstDayOfMonth = today.month(monthIndex).startOf('month');
const weekDay = firstDayOfMonth.day(); // 0 (Sunday) to 6 (Saturday)
const deltaToFirstValidWeekDayInMonth =
(weekDay > weekdayIndex ? 7 : 0) + weekdayIndex - weekDay;
return firstDayOfMonth.add(
(dayRank - 1) * 7 + deltaToFirstValidWeekDayInMonth,
'day',
);
};
const shortcutsItems: PickersShortcutsItem<Dayjs | null>[] = [
{
label: "New Year's Day",
getValue: () => {
// (January 1)
const today = dayjs();
return today.month(0).date(1);
},
},
{
label: 'Birthday of MLK Jr.',
getValue: () => {
// (third Monday in January)
return getMonthWeekday(0, 1, 3);
},
},
{
label: 'Independence Day',
getValue: () => {
// (July 4)
const today = dayjs();
return today.month(6).date(4);
},
},
{
label: 'Labor Day',
getValue: () => {
// (first Monday in September)
return getMonthWeekday(8, 1, 1);
},
},
{
label: 'Thanksgiving Day',
getValue: () => {
// (fourth Thursday in November)
return getMonthWeekday(10, 4, 4);
},
},
{
label: 'Christmas Day',
getValue: () => {
// (December 25)
const today = dayjs();
return today.month(11).date(25);
},
},
];
export default function RTLShortcuts() {
// Inherit the theme from the docs site (dark/light mode)
const existingTheme = useTheme();
const theme = React.useMemo(
() =>
createTheme({}, existingTheme, {
direction: 'rtl',
}),
[existingTheme],
);
return (
<CacheProvider value={cacheRtl}>
<ThemeProvider theme={theme}>
<div dir="rtl">
<LocalizationProvider dateAdapter={AdapterDayjs}>
<StaticDatePicker slotProps={{ shortcuts: { items: shortcutsItems } }} />
</LocalizationProvider>
</div>
</ThemeProvider>
</CacheProvider>
);
}