Fields 컴포넌트
필드 컴포넌트는 사용자가 키보드와 세밀한 키보드 내비게이션으로 날짜와 시간 값을 입력할 수 있게 해 줍니다.
본문
소개 (Introduction)
fields는 어떤 팝오버나 모달 UI를 사용하지 않고 키보드로 날짜나 시간을 입력할 수 있게 해 주는 React 컴포넌트입니다. 화살표 키를 통한 세밀한 내비게이션을 제공하며 지역화와 유효성 검사 같은 고급 동작을 지원합니다.
단일 요소를 편집하는 Fields (Fields to edit a single element)
import dayjs from 'dayjs';
import { DemoContainer, DemoItem } from '@mui/x-date-pickers/internals/demo';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { DateField } from '@mui/x-date-pickers/DateField';
import { TimeField } from '@mui/x-date-pickers/TimeField';
import { DateTimeField } from '@mui/x-date-pickers/DateTimeField';
const defaultValue = dayjs('2022-04-17T15:30');
export default function SingleDateFieldExamples() {
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DemoContainer components={['DateField', 'TimeField', 'DateTimeField']}>
<DemoItem label="DateField">
<DateField defaultValue={defaultValue} />
</DemoItem>
<DemoItem label="TimeField">
<TimeField defaultValue={defaultValue} />
</DemoItem>
<DemoItem label="DateTimeField">
<DateTimeField defaultValue={defaultValue} />
</DemoItem>
</DemoContainer>
</LocalizationProvider>
);
}
범위를 편집하는 Fields (Fields to edit a range)
범위를 편집하는 모든 field는 단일 입력(single input) 버전과 다중 입력(multi-input) 버전이 있습니다.
import dayjs from 'dayjs';
import { DemoContainer, DemoItem } from '@mui/x-date-pickers/internals/demo';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { SingleInputDateRangeField } from '@mui/x-date-pickers-pro/SingleInputDateRangeField';
import { MultiInputDateRangeField } from '@mui/x-date-pickers-pro/MultiInputDateRangeField';
import { SingleInputTimeRangeField } from '@mui/x-date-pickers-pro/SingleInputTimeRangeField';
import { MultiInputTimeRangeField } from '@mui/x-date-pickers-pro/MultiInputTimeRangeField';
import { MultiInputDateTimeRangeField } from '@mui/x-date-pickers-pro/MultiInputDateTimeRangeField';
import { SingleInputDateTimeRangeField } from '@mui/x-date-pickers-pro/SingleInputDateTimeRangeField';
const date1 = dayjs('2022-04-17T15:30');
const date2 = dayjs('2022-04-21T18:30');
export default function DateRangeFieldExamples() {
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DemoContainer
components={[
'SingleInputDateRangeField',
'SingleInputTimeRangeField',
'SingleInputDateTimeRangeField',
'MultiInputDateRangeField',
'MultiInputTimeRangeField',
'MultiInputDateTimeRangeField',
]}
>
<DemoItem label="SingleInputDateRangeField">
<SingleInputDateRangeField defaultValue={[date1, date2]} />
</DemoItem>
<DemoItem label="SingleInputTimeRangeField">
<SingleInputTimeRangeField defaultValue={[date1, date2]} />
</DemoItem>
<DemoItem label="SingleInputDateTimeRangeField">
<SingleInputDateTimeRangeField defaultValue={[date1, date2]} />
</DemoItem>
<DemoItem
label="MultiInputDateRangeField"
component="MultiInputDateRangeField"
>
<MultiInputDateRangeField defaultValue={[date1, date2]} />
</DemoItem>
<DemoItem
label="MultiInputTimeRangeField"
component="MultiInputTimeRangeField"
>
<MultiInputTimeRangeField defaultValue={[date1, date2]} />
</DemoItem>
<DemoItem
label="MultiInputDateTimeRangeField"
component="MultiInputDateTimeRangeField"
>
<MultiInputDateTimeRangeField defaultValue={[date1, date2]} />
</DemoItem>
</DemoContainer>
</LocalizationProvider>
);
}
고급 (Advanced)
섹션이란 무엇인가요? (What is a section?)
field 컴포넌트에서 날짜는 여러 섹션으로 나뉘며, 각 섹션은 날짜 토큰 하나를 편집하는 역할을 합니다.
예를 들어 field에 전달된 형식이 MM/DD/YYYY라면 field는 3개의 섹션을 만듭니다:
MM토큰을 위한month섹션DD토큰을 위한day섹션YYYY토큰을 위한year섹션
이 섹션들은 서로 독립적입니다. day 섹션에 포커스가 있을 때 ArrowUp을 누르면 날짜에 하루가 더해지지만, 달이나 연도는 절대 바뀌지 않습니다.
선택된 섹션 제어 (Control the selected sections)
selectedSections와 onSelectedSectionsChange props을 사용해 현재 선택 중인 섹션을 제어할 수 있습니다.
이 prop은 다음 형식을 받습니다:
- 숫자가 제공되면 해당 인덱스의 섹션이 선택됩니다.
"all"이 제공되면 모든 섹션이 선택됩니다.startIndex와endIndex필드가 있는 객체가 제공되면 두 인덱스 사이의 섹션들이 선택됩니다.FieldSectionType유형의 문자열이 제공되면 해당 이름의 첫 번째 섹션이 선택됩니다.null이 제공되면 선택된 섹션이 없습니다.
:::warning 선택된 섹션을 명령형으로 업데이트하기 전에 입력에 포커스가 있는지 확인해야 합니다. :::
import * as React from 'react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import {
FieldSectionType,
FieldSelectedSections,
FieldRef,
} from '@mui/x-date-pickers/models';
import { PickerValue } from '@mui/x-date-pickers/internals';
import { DateField } from '@mui/x-date-pickers/DateField';
export default function ControlledSelectedSections() {
const [selectedSections, setSelectedSections] =
React.useState<FieldSelectedSections>(null);
const fieldRef = React.useRef<FieldRef<PickerValue>>(null);
const setSelectedSectionType = (selectedSectionType: FieldSectionType) => {
fieldRef.current?.focusField();
setSelectedSections(selectedSectionType);
};
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<Stack spacing={2}>
<Stack direction="row" spacing={2}>
<Button variant="outlined" onClick={() => setSelectedSectionType('month')}>
Month
</Button>
<Button variant="outlined" onClick={() => setSelectedSectionType('day')}>
Day
</Button>
<Button variant="outlined" onClick={() => setSelectedSectionType('year')}>
Year
</Button>
</Stack>
<DateField
fieldRef={fieldRef}
selectedSections={selectedSections}
onSelectedSectionsChange={setSelectedSections}
/>
</Stack>
</LocalizationProvider>
);
}
단일 입력 범위 field와 함께 사용 (Usage with single input range fields)
단일 입력 범위 field의 경우 각 섹션은 시작 날짜와 끝 날짜 양쪽에 모두 존재하므로 섹션 이름으로 단일 섹션을 선택할 수 없습니다.
대신 fieldRef prop으로 섹션의 인덱스를 전달해 전체 섹션 목록에 접근할 수 있습니다:
import * as React from 'react';
import { Dayjs } from 'dayjs';
import Typography from '@mui/material/Typography';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import {
FieldSectionType,
FieldSelectedSections,
FieldRef,
} from '@mui/x-date-pickers/models';
import { DateRange, RangePosition } from '@mui/x-date-pickers-pro/models';
import { SingleInputDateRangeField } from '@mui/x-date-pickers-pro/SingleInputDateRangeField';
export default function ControlledSelectedSectionsSingleInputRangeField() {
const [selectedSections, setSelectedSections] =
React.useState<FieldSelectedSections>(null);
const fieldRef = React.useRef<FieldRef<DateRange<Dayjs>>>(null);
const setSelectedSectionType = (
selectedSectionType: FieldSectionType,
position: RangePosition,
) => {
if (!fieldRef.current) {
return;
}
fieldRef.current.focusField();
const sections = fieldRef.current.getSections().map((el) => el.type);
setSelectedSections(
position === 'start'
? sections.indexOf(selectedSectionType)
: sections.lastIndexOf(selectedSectionType),
);
};
const renderDateHeader = (position: RangePosition) => (
<Stack spacing={2} sx={{ alignItems: 'center' }}>
<Typography sx={{ textTransform: 'capitalize' }}>{position}</Typography>
<Stack direction="row" spacing={1}>
{(['month', 'day', 'year'] as const).map((sectionName) => (
<Button
size="small"
variant="outlined"
onClick={() => setSelectedSectionType(sectionName, position)}
key={sectionName}
>
{sectionName}
</Button>
))}
</Stack>
</Stack>
);
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<Stack spacing={2}>
<Stack spacing={2}>
{renderDateHeader('start')}
{renderDateHeader('end')}
</Stack>
<SingleInputDateRangeField
sx={{ minWidth: 300 }}
fieldRef={fieldRef}
selectedSections={selectedSections}
onSelectedSectionsChange={setSelectedSections}
/>
</Stack>
</LocalizationProvider>
);
}
다중 입력 범위 field와 함께 사용 (Usage with multi-input range fields)
다중 입력 범위 field의 경우 선택된 섹션을 업데이트하기 전에 올바른 입력에 포커스가 있는지만 확인하면 됩니다. 그렇지 않으면 섹션이 잘못된 입력에서 선택될 수 있습니다.
import * as React from 'react';
import Typography from '@mui/material/Typography';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import {
FieldSectionType,
FieldSelectedSections,
FieldRef,
} from '@mui/x-date-pickers/models';
import { PickerValue } from '@mui/x-date-pickers/internals';
import { RangePosition } from '@mui/x-date-pickers-pro/models';
import { MultiInputDateRangeField } from '@mui/x-date-pickers-pro/MultiInputDateRangeField';
export default function ControlledSelectedSectionsMultiInputRangeField() {
const [selectedSections, setSelectedSections] =
React.useState<FieldSelectedSections>(null);
const startFieldRef = React.useRef<FieldRef<PickerValue>>(null);
const endFieldRef = React.useRef<FieldRef<PickerValue>>(null);
const setSelectedSectionType = (
selectedSectionType: FieldSectionType,
position: RangePosition,
) => {
if (position === 'start') {
startFieldRef.current?.focusField();
} else {
endFieldRef.current?.focusField();
}
setSelectedSections(selectedSectionType);
};
const renderDateHeader = (position: RangePosition) => (
<Stack spacing={2} sx={{ alignItems: 'center' }}>
<Typography sx={{ textTransform: 'capitalize' }}>{position}</Typography>
<Stack direction="row" spacing={1}>
{(['month', 'day', 'year'] as const).map((sectionName) => (
<Button
size="small"
variant="outlined"
onClick={() => setSelectedSectionType(sectionName, position)}
>
{sectionName}
</Button>
))}
</Stack>
</Stack>
);
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<Stack spacing={2}>
<Stack spacing={2} sx={{ justifyContent: 'space-between' }}>
{renderDateHeader('start')}
{renderDateHeader('end')}
</Stack>
<MultiInputDateRangeField
sx={{ minWidth: 300 }}
startFieldRef={startFieldRef}
endFieldRef={endFieldRef}
selectedSections={selectedSections}
onSelectedSectionsChange={setSelectedSections}
/>
</Stack>
</LocalizationProvider>
);
}
지우기 동작 (Clearable behavior)
clearable prop을 사용해 field에 지우기 동작을 활성화할 수 있습니다. onClear 콜백 prop으로 이벤트 핸들러를 추가할 수도 있습니다.
:::info 다중 입력 범위 field에서는 지우기 동작이 아직 지원되지 않습니다. :::
import * as React from 'react';
import { Dayjs } from 'dayjs';
import { DemoItem } from '@mui/x-date-pickers/internals/demo';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { DateField } from '@mui/x-date-pickers/DateField';
import Box from '@mui/material/Box';
import Alert from '@mui/material/Alert';
export default function ClearableBehavior() {
const [value, setValue] = React.useState<Dayjs | null>(null);
const [cleared, setCleared] = React.useState<boolean>(false);
React.useEffect(() => {
if (cleared) {
const timeout = setTimeout(() => {
setCleared(false);
}, 1500);
return () => clearTimeout(timeout);
}
return () => {};
}, [cleared]);
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<Box
sx={{
width: '100%',
height: '100%',
display: 'flex',
justifyContent: 'center',
position: 'relative',
}}
>
<DemoItem label="DateField">
<DateField
sx={{ width: '300px' }}
value={value}
onChange={(newValue) => setValue(newValue)}
onClear={() => setCleared(true)}
clearable
/>
</DemoItem>
{cleared && !value && (
<Alert
sx={{ position: 'absolute', bottom: 0, right: 0 }}
severity="success"
>
Field cleared!
</Alert>
)}
</Box>
</LocalizationProvider>
);
}
지우기 IconButton 안에 표시할 아이콘도 사용자 지정할 수 있습니다.
import { DemoContainer } from '@mui/x-date-pickers/internals/demo';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { DateField } from '@mui/x-date-pickers/DateField';
import { SingleInputDateRangeField } from '@mui/x-date-pickers-pro/SingleInputDateRangeField';
import BackspaceIcon from '@mui/icons-material/Backspace';
import HighlightOffIcon from '@mui/icons-material/HighlightOff';
export default function CustomizeClearIcon() {
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DemoContainer components={['DateField', 'SingleInputDateRangeField']}>
<DateField
label="Date Field"
clearable
slots={{ clearIcon: HighlightOffIcon }}
/>
<SingleInputDateRangeField
label="Date Range Field"
clearable
slots={{ clearIcon: BackspaceIcon }}
/>
</DemoContainer>
</LocalizationProvider>
);
}
명령형 API (Imperative API)
fieldRef(또는 다중 입력 field의 경우 startFieldRef와 endFieldRef)의 clearValue, focusField 등 메서드를 사용해 field의 값이나 섹션과 프로그래밍 방식으로 상호작용할 수도 있습니다.
:::success
프로그래밍 방식으로 field에 포커스를 맞출 때는 inputRef.current.focus() 대신 fieldRef.current.focusField()를 사용하세요.
field는 폼 상호운용을 위해 시각적으로 숨겨진 <input>을 렌더링합니다(name, 네이티브 폼 제출, FormData가 예상대로 작동하도록), 그리고 focusField()가 그 숨겨진 요소 대신 보이는 섹션에 안정적으로 포커스를 맞추는 API입니다.
:::
import * as React from 'react';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { DateRangePicker } from '@mui/x-date-pickers-pro/DateRangePicker';
import { MultiInputDateRangeField } from '@mui/x-date-pickers-pro/MultiInputDateRangeField';
import type { MultiInputDateRangeFieldProps } from '@mui/x-date-pickers-pro/MultiInputDateRangeField';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import Button from '@mui/material/Button';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Divider from '@mui/material/Divider';
import { FieldRef } from '@mui/x-date-pickers/models';
import { PickerRangeValue, PickerValue } from '@mui/x-date-pickers/internals';
export default function ImperativeClear() {
const fieldRef = React.useRef<FieldRef<PickerValue>>(null);
const rangeFieldRef = React.useRef<FieldRef<PickerRangeValue>>(null);
const startFieldRef = React.useRef<FieldRef<PickerValue>>(null);
const endFieldRef = React.useRef<FieldRef<PickerValue>>(null);
const CustomMultiInputDateRangeField = React.useCallback(
(props: MultiInputDateRangeFieldProps) => (
<MultiInputDateRangeField
{...props}
startFieldRef={startFieldRef}
endFieldRef={endFieldRef}
/>
),
[],
);
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<Stack spacing={4} sx={{ width: '100%', maxWidth: 600 }}>
<Stack spacing={2}>
<Typography variant="h6">Single Picker (DateField)</Typography>
<Typography variant="body2">
Using <code>fieldRef</code> to clear the value and focus the field.
</Typography>
<Stack direction="row" spacing={2} sx={{ alignItems: 'center' }}>
<DatePicker
slotProps={{ field: { fieldRef }, textField: { fullWidth: true } }}
/>
<Button
variant="outlined"
onClick={() => fieldRef.current?.clearValue()}
sx={{ whiteSpace: 'nowrap' }}
>
Clear
</Button>
<Button
variant="outlined"
onClick={() => fieldRef.current?.focusField()}
sx={{ whiteSpace: 'nowrap' }}
>
Focus
</Button>
</Stack>
</Stack>
<Divider />
<Stack spacing={2}>
<Typography variant="h6">
Single Input Range Picker (DateRangeField)
</Typography>
<Typography variant="body2">
Using <code>fieldRef</code> to clear the value of a single-input range
picker.
</Typography>
<Stack direction="row" spacing={2} sx={{ alignItems: 'center' }}>
<DateRangePicker
slotProps={{
field: { fieldRef: rangeFieldRef },
textField: { fullWidth: true },
}}
/>
<Button
variant="outlined"
onClick={() => rangeFieldRef.current?.clearValue()}
sx={{ whiteSpace: 'nowrap' }}
>
Clear
</Button>
</Stack>
</Stack>
<Divider />
<Stack spacing={2}>
<Typography variant="h6">
Multi Input Range Picker (DateRangeField)
</Typography>
<Typography variant="body2">
Using <code>startFieldRef</code> and <code>endFieldRef</code> to clear
specific fields programmatically in a multi-input range picker.
</Typography>
<DateRangePicker
slots={{ field: CustomMultiInputDateRangeField }}
slotProps={{ textField: { fullWidth: true } }}
/>
</Stack>
<Stack spacing={2}>
<Stack direction="row" spacing={2}>
<Button
variant="outlined"
onClick={() => startFieldRef.current?.clearValue()}
fullWidth
>
Clear Start
</Button>
<Button
variant="outlined"
onClick={() => endFieldRef.current?.clearValue()}
fullWidth
>
Clear End
</Button>
</Stack>
<Stack direction="row" spacing={2}>
<Button
variant="outlined"
onClick={() => startFieldRef.current?.focusField()}
fullWidth
>
Focus Start
</Button>
<Button
variant="outlined"
onClick={() => endFieldRef.current?.focusField()}
fullWidth
>
Focus End
</Button>
</Stack>
</Stack>
</Stack>
</LocalizationProvider>
);
}