본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

DatePicker

원문 보기 위키 갱신

DatePicker (날짜 선택)

DatePicker는 날짜를 선택하거나 입력할 때 사용하는 컴포넌트예요. 입력 박스를 클릭하면 팝업 달력에서 날짜를 선택할 수 있어요.

출처: 문서

본문

언제 사용하나요

입력 박스를 클릭하면 팝업 달력에서 날짜를 선택할 수 있어요.

예제 (Examples)

기본 (Basic)

기본 사용 사례예요. 사용자는 패널에서 날짜를 선택하거나 입력할 수 있어요.

import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Flex } from 'antd';

const onChange: DatePickerProps['onChange'] = (date, dateString) => {
  console.log(date, dateString);
};

const Demo: React.FC = () => (
  <Flex gap="small" justify="flex-start" align="flex-start" vertical>
    <DatePicker onChange={onChange} />
    <DatePicker onChange={onChange} picker="week" />
    <DatePicker onChange={onChange} picker="month" />
    <DatePicker onChange={onChange} picker="quarter" />
    <DatePicker onChange={onChange} picker="year" />
  </Flex>
);

export default Demo;

범위 선택기 (Range Picker)

picker 속성으로 범위 선택기 타입을 설정해요.

import React from 'react';
import { DatePicker, Space } from 'antd';

const { RangePicker } = DatePicker;

const App: React.FC = () => (
  <Space vertical size={12}>
    <RangePicker />
    <RangePicker showTime />
    <RangePicker picker="week" />
    <RangePicker picker="month" />
    <RangePicker picker="quarter" />
    <RangePicker
      picker="year"
      id={{
        start: 'startInput',
        end: 'endInput',
      }}
      onFocus={(_, info) => {
        console.log('Focus:', info.range);
      }}
      onBlur={(_, info) => {
        console.log('Blur:', info.range);
      }}
    />
  </Space>
);

다중 선택 (Multiple)

여러 날짜를 선택해요. showTime과 picker="time"은 지원하지 않아요.

import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Flex } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';

const onChange: DatePickerProps<Dayjs, true>['onChange'] = (date, dateString) => {
  console.log(date, dateString);
};

const defaultValue = [dayjs('2000-01-01'), dayjs('2000-01-03'), dayjs('2000-01-05')];

const App: React.FC = () => (
  <Flex vertical gap="small">
    <DatePicker
      multiple
      onChange={onChange}
      maxTagCount="responsive"
      defaultValue={defaultValue}
      size="small"
    />
    <DatePicker multiple onChange={onChange} maxTagCount="responsive" defaultValue={defaultValue} />
    <DatePicker
      multiple
      onChange={onChange}
      maxTagCount="responsive"
      defaultValue={defaultValue}
      size="large"
    />
  </Flex>
);

확인 필요 (Need Confirm)

DatePicker는 picker 속성에 따라 확인(confirm) 버튼을 표시할지 자동으로 결정해요. needConfirm 속성으로 확인 버튼 표시 여부를 직접 설정할 수도 있어요. needConfirm이 설정되면 사용자는 반드시 확인 버튼을 클릭해야 선택이 완료돼요. 그렇지 않으면 선택기는 포커스를 잃거나 날짜를 선택할 때 선택이 제출돼요.

import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker } from 'antd';
import type { Dayjs } from 'dayjs';

const onChange: DatePickerProps<Dayjs, false>['onChange'] = (date, dateString) => {
  console.log(date, dateString);
};

const App: React.FC = () => <DatePicker onChange={onChange} needConfirm />;

전환 가능한 선택기 (Switchable picker)

Select로 여러 종류의 선택기 사이를 전환해요.

import React, { useState } from 'react';
import type { DatePickerProps, TimePickerProps } from 'antd';
import { DatePicker, Select, Space, TimePicker } from 'antd';
import type { Dayjs } from 'dayjs';

type PickerType = 'time' | 'date';

interface PickerWithTypeProps {
  type: PickerType;
  onChange: TimePickerProps['onChange'] | DatePickerProps<Dayjs, false>['onChange'];
}

const PickerWithType: React.FC<PickerWithTypeProps> = ({ type, onChange }) => {
  if (type === 'time') {
    return <TimePicker onChange={onChange} />;
  }
  if (type === 'date') {
    return <DatePicker onChange={onChange} />;
  }
  return <DatePicker picker={type} onChange={onChange} />;
};

const App: React.FC = () => {
  const [type, setType] = useState<PickerType>('time');

  return (
    <Space>
      <Select
        aria-label="Picker Type"
        value={type}
        onChange={setType}
        options={[
          { label: 'Time', value: 'time' },
          { label: 'Date', value: 'date' },
          { label: 'Week', value: 'week' },
          { label: 'Month', value: 'month' },
          { label: 'Quarter', value: 'quarter' },
          { label: 'Year', value: 'year' },
        ]}
      />
      <PickerWithType type={type} onChange={(value) => console.log(value)} />
    </Space>
  );
};

날짜 포맷 (Date Format)

format으로 날짜 포맷을 설정할 수 있어요. format이 배열이면 입력 박스에 배열의 유효한 포맷 중 어떤 것으로든 입력할 수 있어요.

import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Space } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';

dayjs.extend(customParseFormat);

const { RangePicker } = DatePicker;

const dateFormat = 'YYYY/MM/DD';
const weekFormat = 'MM/DD';
const monthFormat = 'YYYY/MM';

/** Manually entering any of the following formats will perform date parsing */
const dateFormatList = ['DD/MM/YYYY', 'DD/MM/YY', 'DD-MM-YYYY', 'DD-MM-YY'];

const customFormat: DatePickerProps['format'] = (value) =>
  `custom format: ${value.format(dateFormat)}`;

const customWeekStartEndFormat: DatePickerProps['format'] = (value) =>
  `${dayjs(value).startOf('week').format(weekFormat)} ~ ${dayjs(value)
    .endOf('week')
    .format(weekFormat)}`;

const App: React.FC = () => (
  <Space vertical size={12}>
    <DatePicker defaultValue={dayjs('2015/01/01', dateFormat)} format={dateFormat} />
    <DatePicker defaultValue={dayjs('01/01/2015', dateFormatList[0])} format={dateFormatList} />
    <DatePicker defaultValue={dayjs('2015/01', monthFormat)} format={monthFormat} picker="month" />
    <DatePicker defaultValue={dayjs()} format={customWeekStartEndFormat} picker="week" />
    <RangePicker
      defaultValue={[dayjs('2015/01/01', dateFormat), dayjs('2015/01/01', dateFormat)]}
      format={dateFormat}
    />
    <DatePicker defaultValue={dayjs('2015/01/01', dateFormat)} format={customFormat} />
  </Space>
);

시간 선택 (Choose Time)

이 속성은 추가 시간 선택을 제공해요. showTime이 Object면 그 속성이 내장된 TimePicker에 전달돼요.

import React from 'react';
import { DatePicker, Space } from 'antd';
import type { DatePickerProps, GetProps } from 'antd';

type RangePickerProps = GetProps<typeof DatePicker.RangePicker>;

const { RangePicker } = DatePicker;

const onOk = (value: DatePickerProps['value'] | RangePickerProps['value']) => {
  console.log('onOk: ', value);
};

const App: React.FC = () => (
  <Space vertical size={12}>
    <DatePicker
      showTime
      onChange={(value, dateString) => {
        console.log('Selected Time: ', value);
        console.log('Formatted Selected Time: ', dateString);
      }}
      onOk={onOk}
    />
    <RangePicker
      showTime={{ format: 'HH:mm' }}
      format="YYYY-MM-DD HH:mm"
      onChange={(value, dateString) => {
        console.log('Selected Time: ', value);
        console.log('Formatted Selected Time: ', dateString);
      }}
      onOk={onOk}
    />
  </Space>
);

마스크 포맷 (Mask Format)

날짜 포맷을 정렬해요. 화살표 키로 선택을 전환해요. blur 시 날짜를 마지막 유효한 날짜로 정렬하려 합니다.

import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Space } from 'antd';

const onChange: DatePickerProps['onChange'] = (date, dateString) => {
  console.log(date, dateString);
};

const App: React.FC = () => (
  <Space vertical>
    <DatePicker
      format={{
        format: 'YYYY-MM-DD',
        type: 'mask',
      }}
      onChange={onChange}
    />
    <DatePicker
      format={{
        format: 'YYYY-MM-DD HH:mm:ss',
        type: 'mask',
      }}
      onChange={onChange}
    />
  </Space>
);

날짜 범위 제한 (Limit Date Range)

minDate와 maxDate로 선택 가능한 날짜 범위를 제한해요.

import React from 'react';
import { DatePicker } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';

dayjs.extend(customParseFormat);

const dateFormat = 'YYYY-MM-DD';

const App: React.FC = () => (
  <DatePicker
    defaultValue={dayjs('2019-09-03', dateFormat)}
    minDate={dayjs('2019-08-01', dateFormat)}
    maxDate={dayjs('2020-10-31', dateFormat)}
  />
);

비활성 (Disabled)

DatePicker의 비활성 상태예요. 배열로 설정해 입력 중 하나만 비활성화할 수도 있어요.

import React from 'react';
import { DatePicker, Space } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';

dayjs.extend(customParseFormat);

const { RangePicker } = DatePicker;

const dateFormat = 'YYYY-MM-DD';

const App: React.FC = () => (
  <Space vertical size={12}>
    <DatePicker defaultValue={dayjs('2015-06-06', dateFormat)} disabled />
    <DatePicker picker="month" defaultValue={dayjs('2015-06', 'YYYY-MM')} disabled />
    <RangePicker
      defaultValue={[dayjs('2015-06-06', dateFormat), dayjs('2015-06-06', dateFormat)]}
      disabled
    />
    <RangePicker
      defaultValue={[dayjs('2019-09-03', dateFormat), dayjs('2019-11-22', dateFormat)]}
      disabled={[false, true]}
    />
    <DatePicker
      defaultValue={dayjs('2019-09-03', dateFormat)}
      minDate={dayjs('2019-06-01', dateFormat)}
      maxDate={dayjs('2020-06-30', dateFormat)}
    />
  </Space>
);

날짜·시간 비활성 (Disabled Date & Time)

disabledDate와 disabledTime으로 특정 날짜와 시간을 각각 비활성화해요. disabledTime은 showTime과 함께일 때만 동작해요.

import React from 'react';
import { DatePicker, Space } from 'antd';
import type { GetProps } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';

type RangePickerProps = GetProps<typeof DatePicker.RangePicker>;

dayjs.extend(customParseFormat);

const { RangePicker } = DatePicker;

const range = (start: number, end: number) => {
  const result: number[] = [];
  for (let i = start; i < end; i++) {
    result.push(i);
  }
  return result;
};

const disabledDate: RangePickerProps['disabledDate'] = (current) => {
  // Can not select days before today and today
  return current && current < dayjs().endOf('day');
};

const disabledDateForMonth: RangePickerProps['disabledDate'] = (current) => {
  // Can not select months before this month
  return current && current < dayjs().startOf('month');
};

const disabledDateTime = () => ({
  disabledHours: () => range(0, 24).splice(4, 20),
  disabledMinutes: () => range(30, 60),
  disabledSeconds: () => [55, 56],
});

const disabledRangeTime: RangePickerProps['disabledTime'] = (_, type) => {
  if (type === 'start') {
    return {
      disabledHours: () => range(0, 60).splice(4, 20),
      disabledMinutes: () => range(30, 60),
      disabledSeconds: () => [55, 56],
    };
  }
  return {
    disabledHours: () => range(0, 60).splice(20, 4),
    disabledMinutes: () => range(0, 31),
    disabledSeconds: () => [55, 56],
  };
};

const App: React.FC = () => (
  <Space vertical size={12}>
    <DatePicker
      format="YYYY-MM-DD HH:mm:ss"
      disabledDate={disabledDate}
      disabledTime={disabledDateTime}
      showTime={{ defaultOpenValue: dayjs('00:00:00', 'HH:mm:ss') }}
    />
    <DatePicker picker="month" disabledDate={disabledDateForMonth} />
    <RangePicker disabledDate={disabledDate} />
    <RangePicker
      disabledDate={disabledDate}
      disabledTime={disabledRangeTime}
      showTime={{
        hideDisabledOptions: true,
        defaultOpenValue: [dayjs('00:00:00', 'HH:mm:ss'), dayjs('11:59:59', 'HH:mm:ss')],
      }}
      format="YYYY-MM-DD HH:mm:ss"
    />
  </Space>
);

빈 값 허용 (Allow Empty)

RangePicker에서 빈 값을 허용해요. "to date"를 유지해야 할 때 유용해요.

import React from 'react';
import { DatePicker } from 'antd';

const App: React.FC = () => (
  <DatePicker.RangePicker
    placeholder={['Start Date', 'Till Now']}
    allowEmpty={[false, true]}
    onChange={(date, dateString) => {
      console.log(date, dateString);
    }}
  />
);

범위 날짜 선택 (Select range dates)

disabledDate의 info.from을 사용해 동적 날짜 범위 선택을 제한해요.

import React from 'react';
import { DatePicker, Space, Typography } from 'antd';
import type { DatePickerProps } from 'antd';
import type { Dayjs } from 'dayjs';

const { RangePicker } = DatePicker;

const getYearMonth = (date: Dayjs) => date.year() * 12 + date.month();

// Disabled 7 days from the selected date
const disabled7DaysDate: DatePickerProps['disabledDate'] = (current, { from, type }) => {
  if (from) {
    const minDate = from.add(-6, 'days');
    const maxDate = from.add(6, 'days');

    switch (type) {
      case 'year':
        return current.year() < minDate.year() || current.year() > maxDate.year();

      case 'month':
        return (
          getYearMonth(current) < getYearMonth(minDate) ||
          getYearMonth(current) > getYearMonth(maxDate)
        );

      default:
        return Math.abs(current.diff(from, 'days')) >= 7;
    }
  }

  return false;
};

// Disabled 6 months from the selected date
const disabled6MonthsDate: DatePickerProps['disabledDate'] = (current, { from, type }) => {
  if (from) {
    const minDate = from.add(-5, 'months');
    const maxDate = from.add(5, 'months');

    switch (type) {
      case 'year':
        return current.year() < minDate.year() || current.year() > maxDate.year();

      default:
        return (
          getYearMonth(current) < getYearMonth(minDate) ||
          getYearMonth(current) > getYearMonth(maxDate)
        );
    }
  }

  return false;
};

const App: React.FC = () => (
  <Space vertical>
    <Typography.Title level={5}>7 days range</Typography.Title>
    <RangePicker disabledDate={disabled7DaysDate} />

    <Typography.Title level={5}>6 months range</Typography.Title>
    <RangePicker disabledDate={disabled6MonthsDate} picker="month" />
  </Space>
);

프리셋 범위 (Preset Ranges)

사용자 경험을 향상시키기 위해 RangePicker에 프리셋 범위를 설정할 수 있어요. 5.8.0부터 프리셋 값은 콜백 함수를 지원해요.

import React from 'react';
import type { TimeRangePickerProps } from 'antd';
import { DatePicker, Space } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';

const { RangePicker } = DatePicker;

const onChange = (date: Dayjs | null) => {
  if (date) {
    console.log('Date: ', date);
  } else {
    console.log('Clear');
  }
};

const onRangeChange = (dates: null | (Dayjs | null)[], dateStrings: string[]) => {
  if (dates) {
    console.log('From: ', dates[0], ', to: ', dates[1]);
    console.log('From: ', dateStrings[0], ', to: ', dateStrings[1]);
  } else {
    console.log('Clear');
  }
};

const rangePresets: TimeRangePickerProps['presets'] = [
  { label: 'Last 7 Days', value: [dayjs().add(-7, 'd'), dayjs()] },
  { label: 'Last 14 Days', value: [dayjs().add(-14, 'd'), dayjs()] },
  { label: 'Last 30 Days', value: [dayjs().add(-30, 'd'), dayjs()] },
  { label: 'Last 90 Days', value: [dayjs().add(-90, 'd'), dayjs()] },
];

const App: React.FC = () => (
  <Space vertical size={12}>
    <DatePicker
      presets={[
        { label: 'Yesterday', value: dayjs().add(-1, 'd') },
        { label: 'Last Week', value: dayjs().add(-7, 'd') },
        { label: 'Last Month', value: dayjs().add(-1, 'month') },
      ]}
      onChange={onChange}
    />
    <RangePicker presets={rangePresets} onChange={onRangeChange} />
    <RangePicker
      presets={[
        {
          label: <span aria-label="Current Time to End of Day">Now ~ EOD</span>,
          value: () => [dayjs(), dayjs().endOf('day')], // 5.8.0+ support function
        },
        ...rangePresets,
      ]}
      showTime
      format="YYYY/MM/DD HH:mm:ss"
      onChange={onRangeChange}
    />
  </Space>
);

커스터마이즈된 요구사항을 위해 패널에 추가 푸터를 렌더링해요.

import React from 'react';
import { DatePicker, Space } from 'antd';

const { RangePicker } = DatePicker;

const App: React.FC = () => (
  <Space vertical size={12}>
    <DatePicker renderExtraFooter={() => 'extra footer'} />
    <DatePicker renderExtraFooter={() => 'extra footer'} showTime />
    <RangePicker renderExtraFooter={() => 'extra footer'} />
    <RangePicker renderExtraFooter={() => 'extra footer'} showTime />
    <DatePicker renderExtraFooter={() => 'extra footer'} picker="month" />
  </Space>
);

세 가지 크기 (Three Sizes)

입력 박스는 small, medium, large 세 가지 크기가 있어요. size를 생략하면 medium 크기가 사용돼요.

import React, { useState } from 'react';
import type { ConfigProviderProps, RadioChangeEvent } from 'antd';
import { DatePicker, Radio, Space } from 'antd';

type SizeType = ConfigProviderProps['componentSize'];

const { RangePicker } = DatePicker;

const App: React.FC = () => {
  const [size, setSize] = useState<SizeType>('medium');

  const handleSizeChange = (e: RadioChangeEvent) => {
    setSize(e.target.value);
  };

  return (
    <Space vertical size={12}>
      <Radio.Group value={size} onChange={handleSizeChange}>
        <Radio.Button value="large">Large</Radio.Button>
        <Radio.Button value="medium">Medium</Radio.Button>
        <Radio.Button value="small">Small</Radio.Button>
      </Radio.Group>
      <DatePicker size={size} />
      <DatePicker size={size} picker="month" />
      <RangePicker size={size} />
      <DatePicker size={size} picker="week" />
    </Space>
  );
};

셀 렌더링 커스터마이즈 (Customized Cell Rendering)

DatePicker에 cellRender 함수를 제공해 달력의 셀 렌더링을 커스터마이즈할 수 있어요.

import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Space, theme } from 'antd';
import type { Dayjs } from 'dayjs';

const App: React.FC = () => {
  const { token } = theme.useToken();
  const style: React.CSSProperties = {
    border: `${token.lineWidth}px ${token.lineType} ${token.colorPrimary}`,
    borderRadius: '50%',
  };
  const cellRender: DatePickerProps<Dayjs>['cellRender'] = (current, info) => {
    if (info.type !== 'date') {
      return info.originNode;
    }
    if (typeof current === 'number' || typeof current === 'string') {
      return <div className="ant-picker-cell-inner">{current}</div>;
    }
    return (
      <div className="ant-picker-cell-inner" style={current.date() === 1 ? style : {}}>
        {current.date()}
      </div>
    );
  };
  return (
    <Space size={12} vertical>
      <DatePicker cellRender={cellRender} />
      <DatePicker.RangePicker cellRender={cellRender} />
    </Space>
  );
};

패널 커스터마이즈 (Customize Panel)

components로 패널을 대체해요.

import React from 'react';
import type { DatePickerProps } from 'antd';
import { Button, DatePicker, Flex, Slider, Space, Typography } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';

const onChange: DatePickerProps['onChange'] = (date, dateString) => {
  console.log(date, dateString);
};

type DateComponent = Required<NonNullable<DatePickerProps<Dayjs>['components']>>['date'];
type GetProps<T> = T extends React.ComponentType<infer P> ? P : never;

const MyDatePanel = (props: GetProps<DateComponent>) => {
  const { value, onSelect, onHover } = props;

  // Value
  const startDate = React.useMemo(() => dayjs().date(1).month(0), []);
  const [innerValue, setInnerValue] = React.useState(value || startDate);

  React.useEffect(() => {
    if (value) {
      setInnerValue(value);
    }
  }, [value]);

  // Range
  const dateCount = React.useMemo(() => {
    const endDate = startDate.add(1, 'year').add(-1, 'day');
    return endDate.diff(startDate, 'day');
  }, [startDate]);

  const sliderValue = Math.min(Math.max(0, innerValue.diff(startDate, 'day')), dateCount);

  // Render
  return (
    <Flex vertical gap="small" style={{ padding: 16 }}>
      <Typography.Title level={4} style={{ margin: 0 }} title="no, it's not">
        The BEST Picker Panel
      </Typography.Title>
      <Slider
        min={0}
        max={dateCount}
        value={sliderValue}
        onChange={(nextValue) => {
          const nextDate = startDate.add(nextValue, 'day');
          setInnerValue(nextDate);
          onHover?.(nextDate);
        }}
        tooltip={{
          formatter: (nextValue) => startDate.add(nextValue || 0, 'day').format('YYYY-MM-DD'),
        }}
      />
      <Button
        type="primary"
        onClick={() => {
          onSelect(innerValue);
        }}
      >{`That's It!`}</Button>
    </Flex>
  );
};

const App: React.FC = () => (
  <Space vertical>
    <DatePicker
      showNow={false}
      onChange={onChange}
      components={{
        date: MyDatePanel,
      }}
    />
  </Space>
);

외부 패널 사용 (External use panel)

커스텀 메뉴, 외부 선택 패널이에요.

import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import { DatePicker, Dropdown, Space } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';

const DatePickerDemo: React.FC = () => {
  const [visible, setVisible] = React.useState(false);
  const [panelVisible, setPanelVisible] = React.useState(false);

  const [date, setDate] = React.useState<Dayjs | null>(() => dayjs());

  return (
    <Dropdown
      arrow
      open={visible}
      trigger={['click']}
      destroyOnHidden
      onOpenChange={(open) => {
        setVisible(open);
        if (!open) {
          setPanelVisible(false);
        }
      }}
      menu={{
        items: [
          {
            key: 'today',
            label: 'Today',
            onClick() {
              setDate(dayjs());
              setVisible(false);
            },
          },
          {
            key: 'tomorrow',
            label: 'Tomorrow',
            onClick() {
              setDate(dayjs().add(1, 'day'));
              setVisible(false);
            },
          },
          {
            key: 'custom-date',
            label: (
              <div
                style={{ position: 'relative', overflow: 'hidden' }}
                onClick={(e) => {
                  e.stopPropagation();
                  setPanelVisible(true);
                }}
              >
                <div>Customize</div>
                <div
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                >
                  <DatePicker
                    open={panelVisible}
                    styles={{
                      root: {
                        pointerEvents: 'none',
                        opacity: 0,
                        position: 'absolute',
                        bottom: -12,
                        insetInlineStart: 0,
                      },
                    }}
                    onChange={(date) => {
                      setDate(date);
                      setVisible(false);
                      setPanelVisible(false);
                    }}
                  />
                </div>
              </div>
            ),
          },
        ],
      }}
    >
      <Space>
        <span>{date?.format('YYYY-MM-DD')}</span>
        <DownOutlined />
      </Space>
    </Dropdown>
  );
};

const RangePickerDemo: React.FC = () => {
  const [visible, setVisible] = React.useState(false);
  const [panelVisible, setPanelVisible] = React.useState(false);

  const [dates, setDates] = React.useState<[Dayjs, Dayjs] | null>(() => [
    dayjs(),
    dayjs().add(1, 'day'),
  ]);

  return (
    <Dropdown
      arrow
      open={visible}
      trigger={['click']}
      destroyOnHidden
      onOpenChange={(open) => {
        setVisible(open);
        if (!open) {
          setPanelVisible(false);
        }
      }}
      menu={{
        items: [
          {
            key: '7',
            label: '7 days',
            onClick() {
              setDates([dayjs(), dayjs().add(7, 'day')]);
              setVisible(false);
            },
          },
          {
            key: '30',
            label: '30 days',
            onClick() {
              setDates([dayjs(), dayjs().add(30, 'day')]);
              setVisible(false);
            },
          },
          {
            key: 'custom-date',
            label: (
              <div
                style={{ position: 'relative', overflow: 'hidden' }}
                onClick={(e) => {
                  e.stopPropagation();
                  setPanelVisible(true);
                }}
              >
                <div>Customize</div>
                <div
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                >
                  <DatePicker.RangePicker
                    open={panelVisible}
                    styles={{
                      root: {
                        pointerEvents: 'none',
                        opacity: 0,
                        position: 'absolute',
                        bottom: 0, // RangePicker use this style
                        insetInlineStart: 0,
                      },
                    }}
                    onChange={(ranges) => {
                      if (ranges?.[0] && ranges?.[1]) {
                        setDates([ranges[0], ranges[1]]);
                      } else {
                        setDates(null);
                      }
                      setVisible(false);
                      setPanelVisible(false);
                    }}
                  />
                </div>
              </div>
            ),
          },
        ],
      }}
    >
      <Space>
        <span>
          {dates
            ? `${dates[0].format('YYYY-MM-DD')} ~ ${dates[1].format('YYYY-MM-DD')}`
            : 'Select range'}
        </span>
        <DownOutlined />
      </Space>
    </Dropdown>
  );
};

const Demo = () => {
  return (
    <div style={{ display: 'flex', gap: '20%' }}>
      <div>
        <div style={{ marginBottom: 12 }}>DatePicker</div>
        <DatePickerDemo />
      </div>

      <div>
        <div style={{ marginBottom: 12 }}>RangePicker</div>
        <RangePickerDemo />
      </div>
    </div>
  );
};

불교 연대 (Buddhist Era)

locale을 사용해 특별한 달력 포맷을 지원해요.

import React from 'react';
import { ConfigProvider, DatePicker, Space, Typography } from 'antd';
import type { DatePickerProps } from 'antd';
import en from 'antd/es/date-picker/locale/en_US';
import enUS from 'antd/es/locale/en_US';
import dayjs from 'dayjs';
import buddhistEra from 'dayjs/plugin/buddhistEra';

dayjs.extend(buddhistEra);

const { Title } = Typography;

// Component level locale
const buddhistLocale: typeof en = {
  ...en,
  lang: {
    ...en.lang,
    fieldDateFormat: 'BBBB-MM-DD',
    fieldDateTimeFormat: 'BBBB-MM-DD HH:mm:ss',
    yearFormat: 'BBBB',
    cellYearFormat: 'BBBB',
  },
};

// ConfigProvider level locale
const globalBuddhistLocale: typeof enUS = {
  ...enUS,
  DatePicker: {
    ...enUS.DatePicker!,
    lang: buddhistLocale.lang,
  },
};

const defaultValue = dayjs('2024-01-01');

const App: React.FC = () => {
  const onChange: DatePickerProps['onChange'] = (_, dateStr) => {
    console.log('onChange:', dateStr);
  };

  return (
    <Space vertical>
      <Title level={4}>By locale props</Title>
      <DatePicker defaultValue={defaultValue} locale={buddhistLocale} onChange={onChange} />
      <DatePicker
        defaultValue={defaultValue}
        showTime
        locale={buddhistLocale}
        onChange={onChange}
      />

      <Title level={4}>By ConfigProvider</Title>
      <ConfigProvider locale={globalBuddhistLocale}>
        <Space vertical>
          <DatePicker defaultValue={defaultValue} onChange={onChange} />
          <DatePicker defaultValue={defaultValue} showTime onChange={onChange} />
        </Space>
      </ConfigProvider>
    </Space>
  );
};

상태 (Status)

status로 DatePicker에 상태를 추가해요. error나 warning일 수 있어요.

import React from 'react';
import { DatePicker, Space } from 'antd';

const App: React.FC = () => (
  <Space vertical style={{ width: '100%' }}>
    <DatePicker status="error" style={{ width: '100%' }} />
    <DatePicker status="warning" style={{ width: '100%' }} />
    <DatePicker.RangePicker status="error" style={{ width: '100%' }} />
    <DatePicker.RangePicker status="warning" style={{ width: '100%' }} />
  </Space>
);

변형 (Variants)

DatePicker의 변형으로 outlined filled borderless underlined 네 가지가 있어요.

import React from 'react';
import { DatePicker, Flex } from 'antd';

const { RangePicker } = DatePicker;

const App: React.FC = () => (
  <Flex vertical gap={12}>
    <Flex gap={8}>
      <DatePicker placeholder="Outlined" />
      <RangePicker placeholder={['Outlined Start', 'Outlined End']} />
    </Flex>
    <Flex gap={8}>
      <DatePicker placeholder="Filled" variant="filled" />
      <RangePicker placeholder={['Filled Start', 'Filled End']} variant="filled" />
    </Flex>
    <Flex gap={8}>
      <DatePicker placeholder="Borderless" variant="borderless" />
      <RangePicker placeholder={['Borderless Start', 'Borderless End']} variant="borderless" />
    </Flex>
    <Flex gap={8}>
      <DatePicker placeholder="Underlined" variant="underlined" />
      <RangePicker placeholder={['Underlined Start', 'Underlined End']} variant="underlined" />
    </Flex>
  </Flex>
);

커스텀 시맨틱 DOM 스타일링

classNames와 styles에 객체/함수를 전달해 DatePicker의 시맨틱 DOM 스타일을 커스터마이즈할 수 있어요.

import React from 'react';
import { DatePicker, Flex } from 'antd';
import type { DatePickerProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
import type { Dayjs } from 'dayjs';

const useStyles = createStyles(({ token }) => ({
  root: {
    border: `${token.lineWidth}px ${token.lineType} ${token.colorPrimary}`,
    width: 200,
  },
}));

const stylesObject: DatePickerProps<Dayjs>['styles'] = {
  input: { fontStyle: 'italic' },
  suffix: { opacity: 0.85 },
};

const stylesFn: DatePickerProps<Dayjs>['styles'] = (
  info,
): GetProp<DatePickerProps<Dayjs>, 'styles', 'Return'> => {
  if (info.props.size === 'large') {
    return {
      root: { borderColor: '#722ed1' },
      popup: {
        container: { border: '1px solid #722ed1', borderRadius: 8 },
      },
    };
  }
  return {};
};

const App: React.FC = () => {
  const { styles: classNames } = useStyles();
  return (
    <Flex vertical gap="medium">
      <DatePicker classNames={classNames} styles={stylesObject} placeholder="Object" />
      <DatePicker classNames={classNames} styles={stylesFn} placeholder="Function" size="large" />
    </Flex>
  );
};

export default App;

Placement

placement를 이용해 팝업의 위치를 직접 지정할 수 있어요.

import React, { useState } from 'react';
import type { DatePickerProps, RadioChangeEvent } from 'antd';
import { DatePicker, Radio } from 'antd';

const { RangePicker } = DatePicker;

const App: React.FC = () => {
  const [placement, setPlacement] = useState<DatePickerProps['placement']>('topLeft');

  const placementChange = (e: RadioChangeEvent) => {
    setPlacement(e.target.value);
  };

  return (
    <>
      <Radio.Group value={placement} onChange={placementChange}>
        <Radio.Button value="topLeft">topLeft</Radio.Button>
        <Radio.Button value="topRight">topRight</Radio.Button>
        <Radio.Button value="bottomLeft">bottomLeft</Radio.Button>
        <Radio.Button value="bottomRight">bottomRight</Radio.Button>
      </Radio.Group>
      <br />
      <br />
      <DatePicker placement={placement} />
      <br />
      <br />
      <RangePicker placement={placement} />
    </>
  );
};

export default App;

Prefix and Suffix

prefix와 suffixIcon을 커스터마이즈할 수 있어요.

import React from 'react';
import { SmileOutlined } from '@ant-design/icons';
import { DatePicker, Space } from 'antd';
import type { Dayjs } from 'dayjs';

const smileIcon = <SmileOutlined />;
const { RangePicker } = DatePicker;

const onChange = (date: Dayjs | (Dayjs | null)[] | null, dateString: string | string[] | null) => {
  console.log(date, dateString);
};

const App: React.FC = () => (
  <Space vertical size={12}>
    <DatePicker suffixIcon={smileIcon} onChange={onChange} />
    <DatePicker suffixIcon={smileIcon} onChange={onChange} picker="month" />
    <RangePicker suffixIcon={smileIcon} onChange={onChange} />
    <DatePicker suffixIcon={smileIcon} onChange={onChange} picker="week" />
    <DatePicker suffixIcon="ab" onChange={onChange} />
    <DatePicker suffixIcon="ab" onChange={onChange} picker="month" />
    <RangePicker suffixIcon="ab" onChange={onChange} />
    <DatePicker suffixIcon="ab" onChange={onChange} picker="week" />
    <DatePicker prefix={smileIcon} onChange={onChange} picker="week" />
    <DatePicker prefix="Event Period" onChange={onChange} picker="week" />
    <RangePicker prefix={smileIcon} onChange={onChange} picker="week" />
    <RangePicker prefix="Event Period" onChange={onChange} picker="week" />
  </Space>
);

export default App;

API

공통 props 참고: Common props

선택기(picker)는 다음과 같이 여섯 종류가 있어요:

  • DatePicker
  • DatePicker[picker="month"]
  • DatePicker[picker="week"]
  • DatePicker[picker="year"]
  • DatePicker[picker="quarter"] (4.1.0에서 추가)
  • RangePicker

로컬라이제이션 (Localization)

기본 로케일은 en-US예요. 다른 언어가 필요하다면 진입점(entry)에서 제공되는 국제화 컴포넌트 사용을 권장해요. ConfigProvider를 참고하세요.

특별한 요구(단일 컴포넌트 언어만 수정)가 있다면 locale 속성을 사용하세요. 예시: default.

// The default locale is en-US, if you want to use other locale, just set locale in entry file globally.
// Make sure you import the relevant dayjs file as well, otherwise the locale won't change for all texts (e.g. range picker months)
import locale from 'antd/locale/zh_CN';
import dayjs from 'dayjs';

import 'dayjs/locale/zh-cn';

dayjs.locale('zh-cn');

<ConfigProvider locale={locale}>
  <DatePicker defaultValue={dayjs('2015-01-01', 'YYYY-MM-DD')} />
</ConfigProvider>;

:::warning Next.js App Router를 사용할 때는 Day.js 로케일 파일을 import하기 전에 'use client'를 추가해야 해요. Ant Design 컴포넌트는 모두 클라이언트에서만 동작하기 때문에, RSC에서 로케일 파일을 import하면 동작하지 않아요. :::

공통 API (Common API)

다음 API는 DatePicker, RangePicker에서 공통으로 사용돼요.

Property Description Type Default Version Global Config
allowClear Customize clear button boolean | { clearIcon?: ReactNode } true 5.8.0: Support object type 6.4.0
bordered Whether has border style, please use variant instead boolean true - ×
className The picker className string - DatePicker: 5.7.0, RangePicker: 5.11.0
classNames Customize class for each semantic structure inside the component. Supports object or function. Record<SemanticDOM, string> | (info: { props })=> Record<SemanticDOM, string> - DatePicker: 5.25.0, RangePicker: 5.25.0
dateRender Custom rendering function for date cells, >= 5.4.0 use cellRender instead. function(currentDate: dayjs, today: dayjs) => React.ReactNode - < 5.4.0 ×
cellRender Custom rendering function for picker cells (current: dayjs, info: { originNode: React.ReactElement,today: DateType, range?: 'start' | 'end', type: PanelMode, locale?: Locale, subType?: 'hour' | 'minute' | 'second' | 'meridiem' }) => React.ReactNode - 5.4.0 ×
components Custom panels Record<Panel | 'input', React.ComponentType> - 5.14.0 ×
defaultOpen Initial open state of picker boolean - ×
disabled Determine whether the DatePicker is disabled boolean false ×
disabledDate Specify the date that cannot be selected (currentDate: dayjs, info: { from?: dayjs, type: Picker }) => boolean - info: 5.14.0 ×
dropdownClassName The className of popup calendar, please use classNames.popup.root instead string - - ×
format To set the date format, support multi-format matching when it is an array, display the first one shall prevail. refer to dayjs#format. for example: Custom Format formatType @rc-component/picker ×
order Auto order date when multiple or range selection boolean true 5.14.0 ×
popupClassName To customize the className of the popup calendar, use classNames.popup.root instead string - 4.23.0 ×
preserveInvalidOnBlur Don't clear the input on blur even when the typed value is invalid boolean false 5.14.0 ×
getPopupContainer To set the container of the floating layer, while the default is to create a div element in body function(trigger) - ×
inputReadOnly Set the readonly attribute of the input tag (avoids virtual keyboard on touch devices) boolean false ×
locale Localization configuration object default ×
minDate The minimum date, which also limits the range of panel switching dayjs - 5.14.0 ×
maxDate The maximum date, which also limits the range of panel switching dayjs - 5.14.0 ×
mode The picker panel mode( Cannot select year or month anymore? ) time | date | month | year | decade - ×
needConfirm Need click confirm button to trigger value change. Default false when multiple boolean - 5.14.0 ×
nextIcon The custom next icon ReactNode - 4.17.0 ×
open The open state of picker boolean - ×
panelRender Customize panel render (panelNode) => ReactNode - 4.5.0 ×
picker Set picker type date | week | month | quarter | year date quarter: 4.1.0 ×
placeholder The placeholder of date input string | [string,string] - ×
placement The position where the selection box pops up bottomLeft bottomRight topLeft topRight bottomLeft ×
popupStyle To customize the style of the popup calendar, use styles.popup.root instead CSSProperties {} ×
prefix The custom prefix ReactNode - 5.22.0 ×
presets The preset ranges for quick selection, Since 5.8.0, preset value supports callback function. { label: React.ReactNode, value: Dayjs | (() => Dayjs) }[] - ×
prevIcon The custom prev icon ReactNode - 4.17.0 ×
previewValue When the user selects the date hover option, the value of the input field undergoes a temporary change false | hover hover 6.0.0 ×
size To determine the size of the input box, the height of large and small, are 40px and 24px respectively, while default size is 32px large | medium | small - ×
status Set validation status 'error' | 'warning' - 4.19.0 ×
style To customize the style of the input box CSSProperties {} DatePicker: 5.7.0, RangePicker: 5.11.0
styles Customize inline style for each semantic structure inside the component. Supports object or function. Record<SemanticDOM, CSSProperties> | (info: { props })=> Record<SemanticDOM, CSSProperties> - DatePicker: 5.25.0, RangePicker: 5.25.0
suffixIcon The custom suffix icon ReactNode - DatePicker: 6.3.0, RangePicker: 6.4.0
superNextIcon The custom super next icon ReactNode - 4.17.0 ×
superPrevIcon The custom super prev icon ReactNode - 4.17.0 ×
clearIcon (Only supports global configuration) Custom clear icon ReactNode - × 6.4.0
variant Variants of picker outlined | borderless | filled | underlined outlined 5.13.0 | underlined: 5.24.0 DatePicker: 5.19.0, RangePicker: 5.19.0
onClear Callback when click the clear button () => void - 6.5.0 ×
onOpenChange Callback function, can be executed whether the popup calendar is popped up or closed function(open) - ×
onPanelChange Callback when picker panel mode is changed function(value, mode) - ×
onSelect Callback when a date is selected, please use onCalendarChange instead function(value) - - ×

공통 메서드 (Common Methods)

Name Description Version
blur() Remove focus
focus() Get focus

DatePicker

Property Description Type Default Version
defaultPickerValue Default panel date, will be reset when panel open dayjs - 5.14.0
defaultValue To set default date, if start time or end time is null or undefined, the date range will be an open interval dayjs -
disabledTime To specify the time that cannot be selected function(date) -
format To set the date format. refer to dayjs#format formatType YYYY-MM-DD
multiple Enable multiple selection. Not support showTime boolean false 5.14.0
pickerValue Panel date. Used for controlled switching of panel date. Work with onPanelChange dayjs - 5.14.0
renderExtraFooter Render extra footer in panel (mode) => React.ReactNode -
showNow Show the fast access of current datetime boolean - 4.4.0
showTime To provide an additional time selection object | boolean TimePicker Options
showTime.defaultValue Use showTime.defaultOpenValue instead dayjs dayjs() 5.27.3
showTime.defaultOpenValue To set default time of selected date, demo dayjs dayjs()
showWeek Show week info when in DatePicker boolean false 5.14.0
value To set date dayjs -
onChange Callback function, can be executed when the selected time is changing function(date: dayjs | null, dateString: string | null) -
onOk Callback when click ok button function() -
onPanelChange Callback function for panel changing function(value, mode) -

DatePicker[picker=year]

Property Description Type Default Version
defaultValue To set default date dayjs -
format To set the date format. refer to dayjs#format formatType YYYY
multiple Enable multiple selection boolean false 5.14.0
renderExtraFooter Render extra footer in panel () => React.ReactNode -
tagRender Customize tag render, only applies when multiple is set (props) => ReactNode - 6.4.0
value To set date dayjs -
onChange Callback function, can be executed when the selected time is changing function(date: dayjs | null, dateString: string | null) -

DatePicker[picker=quarter]

4.1.0에서 추가됐어요.

Property Description Type Default Version
defaultValue To set default date dayjs -
format To set the date format. refer to dayjs#format formatType YYYY-\QQ
multiple Enable multiple selection boolean false 5.14.0
renderExtraFooter Render extra footer in panel () => React.ReactNode -
tagRender Customize tag render, only applies when multiple is set (props) => ReactNode - 6.4.0
value To set date dayjs -
onChange Callback function, can be executed when the selected time is changing function(date: dayjs | null, dateString: string | null) -

DatePicker[picker=month]

Property Description Type Default Version
defaultValue To set default date dayjs -
format To set the date format. refer to dayjs#format formatType YYYY-MM
multiple Enable multiple selection boolean false 5.14.0
renderExtraFooter Render extra footer in panel () => React.ReactNode -
tagRender Customize tag render, only applies when multiple is set (props) => ReactNode - 6.4.0
value To set date dayjs -
onChange Callback function, can be executed when the selected time is changing function(date: dayjs | null, dateString: string | null) -

DatePicker[picker=week]

Property Description Type Default Version
defaultValue To set default date dayjs -
format To set the date format. refer to dayjs#format formatType YYYY-wo
multiple Enable multiple selection boolean false 5.14.0
renderExtraFooter Render extra footer in panel (mode) => React.ReactNode -
tagRender Customize tag render, only applies when multiple is set (props) => ReactNode - 6.4.0
value To set date dayjs -
onChange Callback function, can be executed when the selected time is changing function(date: dayjs | null, dateString: string | null) -
showWeek Show week info when in DatePicker boolean true 5.14.0

RangePicker

Property Description Type Default Version Global Config
allowEmpty Allow start or end input leave empty [boolean, boolean] [false, false] ×
cellRender Custom rendering function for picker cells (current: dayjs, info: { originNode: React.ReactElement,today: DateType, range?: 'start' | 'end', type: PanelMode, locale?: Locale, subType?: 'hour' | 'minute' | 'second' | 'meridiem' }) => React.ReactNode - 5.4.0 ×
dateRender Custom rendering function for date cells, >= 5.4.0 use cellRender instead. function(currentDate: dayjs, today: dayjs) => React.ReactNode - < 5.4.0 ×
defaultPickerValue Default panel date, will be reset when panel open [dayjs, dayjs] - 5.14.0 ×
defaultValue To set default date [dayjs, dayjs] - ×
disabled If disable start or end [boolean, boolean] - ×
disabledTime To specify the time that cannot be selected function(date: dayjs, partial: start | end, info: { from?: dayjs }) - info.from: 5.17.0 ×
format To set the date format. refer to dayjs#format formatType YYYY-MM-DD HH:mm:ss ×
id Config input ids { start?: string, end?: string } - 5.14.0 ×
pickerValue Panel date. Used for controlled switching of panel date. Work with onPanelChange [dayjs, dayjs] - 5.14.0 ×
presets The preset ranges for quick selection, Since 5.8.0, preset value supports callback function. { label: React.ReactNode, value: [(Dayjs | (() => Dayjs)), (Dayjs | (() => Dayjs))] }[] - ×
renderExtraFooter Render extra footer in panel () => React.ReactNode - ×
separator Set separator between inputs React.ReactNode <SwapRightOutlined /> 6.3.0
showTime To provide an additional time selection object | boolean TimePicker Options ×
showTime.defaultValue Use showTime.defaultOpenValue instead [dayjs, dayjs] [dayjs(), dayjs()] 5.27.3 ×
showTime.defaultOpenValue To set default time of selected date, demo [dayjs, dayjs] [dayjs(), dayjs()] ×
value To set date [dayjs, dayjs] - ×
onCalendarChange Callback function, can be executed when the start time or the end time of the range is changing. info argument is added in 4.4.0 function(dates: [dayjs, dayjs], dateStrings: [string, string], info: { range:start|end }) - ×
onChange Callback function, can be executed when the selected time is changing function(dates: [dayjs, dayjs] | null, dateStrings: [string, string] | null) - ×
onFocus Trigger when get focus function(event, { range: 'start' | 'end' }) - range: 5.14.0 ×
onBlur Trigger when lose focus function(event, { range: 'start' | 'end' }) - range: 5.14.0 ×

formatType

import type { Dayjs } from 'dayjs';

type Generic = string;
type GenericFn = (value: Dayjs) => string;

export type FormatType =
  | Generic
  | GenericFn
  | Array<Generic | GenericFn>
  | {
      format: string;
      type?: 'mask';
    };

참고: type은 5.14.0에서 추가됐어요.

Semantic DOM

https://ant.design/components/date-picker/semantic.md

Design Token

Component Token (DatePicker)

Token Name Description Type Default Value
activeBg Background color when the input box is activated string #ffffff
activeBorderColor Active border color string #1677ff
activeShadow Box-shadow when active string 0 0 0 2px rgba(5,145,255,0.1)
addonBg Background color of addon string rgba(0,0,0,0.02)
cellActiveWithRangeBg Background color of cell in range string #e6f4ff
cellBgDisabled Background color of disabled cell string rgba(0,0,0,0.04)
cellHeight Height of cell number 24
cellHoverBg Background color of cell hover state string rgba(0,0,0,0.04)
cellHoverWithRangeBg Background color of hovered cell in range string #cbe0fd
cellRangeBorderColor Border color of cell in range when picking string #82b4f9
cellWidth Width of cell number 36
errorActiveShadow Box-shadow when active in error status string 0 0 0 2px rgba(255,38,5,0.06)
hoverBg Background color when the input box hovers string #ffffff
hoverBorderColor Hover border color string #4096ff
inputFontSize Font size number 14
inputFontSizeLG Font size of large number 16
inputFontSizeSM Font size of small number 14
multipleItemBg Background color of multiple tag string rgba(0,0,0,0.06)
multipleItemBorderColor Border color of multiple tag string transparent
multipleItemBorderColorDisabled Border color of multiple tag when disabled string transparent
multipleItemColorDisabled Text color of multiple tag when disabled string rgba(0,0,0,0.25)
multipleItemHeight Height of multiple tag number 24
multipleItemHeightLG Height of multiple tag with large size number 32
multipleItemHeightSM Height of multiple tag with small size number 16
multipleSelectorBgDisabled Background color of multiple selector when disabled string rgba(0,0,0,0.04)
paddingBlock Vertical padding of input number 4
paddingBlockLG Vertical padding of large input number 7
paddingBlockSM Vertical padding of small input number 0
paddingInline Horizontal padding of input number 11
paddingInlineLG Horizontal padding of large input number 11
paddingInlineSM Horizontal padding of small input number 7
presetsMaxWidth Max width of preset area number 200
presetsWidth Width of preset area number 120
textHeight Height of cell text number 40
timeCellHeight Height of time cell number 28
timeColumnHeight Height of time column number 224
timeColumnWidth Width of time column number 56
warningActiveShadow Box-shadow when active in warning status string 0 0 0 2px rgba(255,215,5,0.1)
withoutTimeCellHeight Height of decade/year/quarter/month/week cell number 66
zIndexPopup z-index of popup number 1050

Global Token

Token Name Description Type Default Value
borderRadius Border radius of base components number
borderRadiusLG LG size border radius, used in some large border radius components, such as Card, Modal and other components. number
borderRadiusSM SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size number
borderRadiusXS XS size border radius, used in some small border radius components, such as Segmented, Arrow and other components with small border radius. number
boxShadowSecondary Control the secondary box shadow style of an element. string
colorBgContainer Container background color, e.g: default button, input box, etc. Be sure not to confuse this with colorBgElevated. string
colorBgContainerDisabled Control the background color of container in disabled state. string
colorBgElevated Container background color of the popup layer, in dark mode the color value of this token will be a little brighter than colorBgContainer. E.g: modal, pop-up, menu, etc. string
colorBorder Default border color, used to separate different elements, such as: form separator, card separator, etc. string
colorBorderDisabled Control the border color of the element in the disabled state. string
colorError Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. string
colorErrorAffix Control the color of form control prefix/suffix in error state. string
colorErrorBg The background color of the error state. string
colorErrorBgHover The hover state background color of the error state. string
colorErrorBorderHover The hover state border color of the error state. string
colorErrorText The default state of the text in the error color. string
colorFillSecondary The second level of fill color can outline the shape of the element more clearly, such as Rate, Skeleton, etc. It can also be used as the Hover state of the third level of fill color, such as Table, etc. string
colorFillTertiary The third level of fill color is used to outline the shape of the element, such as Slider, Segmented, etc. If there is no emphasis requirement, it is recommended to use the third level of fill color as the default fill color. string
colorIcon Weak action. Such as allowClear or Alert close button string
colorIconHover Weak action hover color. Such as allowClear or Alert close button string
colorPrimary Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. string
colorPrimaryBorder The stroke color under the main color gradient, used on the stroke of components such as Slider. string
colorSplit Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. string
colorText Default text color which comply with W3C standards, and this color is also the darkest neutral color. string
colorTextDisabled Control the color of text in disabled state. string
colorTextHeading Control the font color of heading. string
colorTextLightSolid Control the highlight color of text with background color, such as the text in Primary Button components. string
colorTextPlaceholder Control the color of placeholder text. string
colorTextQuaternary The fourth level of text color is the lightest text color, such as form input prompt text, disabled color text, etc. string
colorTextTertiary The third level of text color is generally used for descriptive text, such as form supplementary explanation text, list descriptive text, etc. string
colorWarning Used to represent the warning map token, such as Notification, Alert, etc. Alert or Control component(like Input) will use these map tokens. string
colorWarningAffix Control the color of form control prefix/suffix in warning state. string
colorWarningBg The background color of the warning state. string
colorWarningBgHover The hover state background color of the warning state. string
colorWarningBorderHover The hover state border color of the warning state. string
colorWarningText The default state of the text in the warning color. string
controlHeight The height of the basic controls such as buttons and input boxes in Ant Design number
controlHeightLG LG component height number
controlHeightSM SM component height number
controlItemBgActive Control the background color of control component item when active. string
fontFamily The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. string
fontSize The most widely used font size in the design system, from which the text gradient will be derived. number
fontSizeLG Large font size number
fontSizeSM Small font size number
fontWeightStrong Control the font weight of heading components (such as h1, h2, h3) or selected item. number
lineHeight Line height of text. number
lineHeightLG Line height of large text. number
lineType Border style of base components string
lineWidth Border width of base components number
lineWidthBold The default line width of the outline class components, such as Button, Input, Select, etc. number
marginXS Control the margin of an element, with a small size. number
marginXXS Control the margin of an element, with the smallest size. number
motionDurationMid Motion speed, medium speed. Used for medium element animation interaction. string
motionDurationSlow Motion speed, slow speed. Used for large element animation interaction. string
motionEaseInOutCirc Preset motion curve. string
motionEaseInQuint Preset motion curve. string
motionEaseOutCirc Preset motion curve. string
motionEaseOutQuint Preset motion curve. string
padding Control the padding of the element. number
paddingSM Control the small padding of the element. number
paddingXS Control the extra small padding of the element. number
paddingXXS Control the extra extra small padding of the element. number
sizePopupArrow The size of the component arrow number

FAQ

mode를 DatePicker/RangePicker로 설정했는데 더 이상 연도나 월을 선택할 수 없어요? {#faq-mode-cannot-select}

FAQ를 참고하세요.

날짜 선택기에서 연도를 선택한 뒤 월 패널이 아니라 날짜 패널로 바로 전환되는 이유는 뭔가요? {#faq-year-to-date-panel}

연도를 선택한 뒤 시스템이 월 패널이 아니라 바로 날짜 패널로 전환돼요. 이 디자인은 사용자가 월 선택 화면에 다시 들어가지 않고도 한 번의 클릭으로 연도 수정을 완료할 수 있도록 해 조작 부담을 줄이기 위한 거예요. 동시에 월을 기억해야 하는 추가적인 인지 부담도 피할 수 있어요.

Moment.js 같은 커스텀 날짜 라이브러리와 DatePicker를 함께 쓰려면 어떻게 해야 하나요? {#faq-custom-date-library}

커스텀 날짜 라이브러리 사용 문서를 참고하세요.

dayjs.locale을 전역으로 설정했는데 왜 동작하지 않나요? {#faq-locale-not-work}

DatePicker는 v4에서 기본적으로 locale을 en으로 설정해요. 대신 DatePicker의 locale prop이나 ConfigProvider의 locale prop을 설정할 수 있어요.

날짜 관련 컴포넌트의 로케일이 동작하지 않아요?

FAQ Date-related-components-locale-is-not-working?를 참고하세요.

주(week) 시작 요일을 수정하려면 어떻게 해야 하나요? {#faq-week-start-day}

올바른 언어 설정 (#5605)을 사용하거나, dayjs locale 설정을 업데이트하세요:

import dayjs from 'dayjs';

import 'dayjs/locale/zh-cn';

import updateLocale from 'dayjs/plugin/updateLocale';

dayjs.extend(updateLocale);
dayjs.updateLocale('zh-cn', {
  weekStart: 0,
});

panelRender를 사용할 때 원본 패널이 전환되지 않는 이유는 뭔가요? {#faq-panel-render-switch}

panelRender로 노드의 레이아웃을 바꾸면 React가 해당 컴포넌트를 언마운트했다가 다시 마운트하면서 상태가 초기화돼요. 레이아웃을 안정적으로 유지해야 해요. 자세한 내용은 #27263을 참고하세요.

비활성(disabled) 시간과 날짜를 어떻게 이해해야 하나요? {#faq-disabled-date-time}

'날짜 비활성화가 왜 이렇게 어려운가요?' 블로그를 참고해 사용 방법을 익혀보세요.

더 알아보기 (Learn more)