MonthPicker

MonthPicker

인라인(inline) 월, 여러 월, 월 범위를 선택하는 피커 컴포넌트예요.

출처: 문서

본문

사용법 (Usage)

MonthPicker로 단일 월, 여러 월, 월 범위를 인라인으로 선택할 수 있어요.

import { useState } from 'react';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  const [value, setValue] = useState<Date | null>(null);
  return <MonthPicker value={value} onChange={setValue} />;
}

선택 해제 허용 (Allow deselect)

allowDeselect를 설정하면 사용자가 현재 선택된 날짜를 클릭해 선택을 해제할 수 있어요. allowDeselect는 type prop이 range 또는 multiple일 때 무시돼요. 날짜가 선택 해제되면 onChange가 null로 호출돼요.

import { useState } from 'react';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  const [value, setValue] = useState<Date | null>(null);
  return <MonthPicker value={value} onChange={setValue} allowDeselect />;
}

여러 날짜 (Multiple dates)

type="multiple"을 설정하면 사용자가 여러 날짜를 선택할 수 있어요.

import { useState } from 'react';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  const [value, setValue] = useState<Date[]>([]);
  return <MonthPicker type="multiple" value={value} onChange={setValue} />;
}

날짜 범위 (Dates range)

type="range"를 설정하면 사용자가 날짜 범위를 선택할 수 있어요.

import { useState } from 'react';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  const [value, setValue] = useState<[Date | null, Date | null]>([null, null]);
  return <MonthPicker type="range" value={value} onChange={setValue} />;
}

범위에서 단일 날짜 (Single date in range)

기본적으로 범위로 단일 날짜를 선택하는 것은 허용되지 않아요. 사용자가 같은 날짜를 두 번째로 클릭하면 선택이 해제돼요. 이 동작을 바꾸려면 allowSingleDateInRange prop을 설정해요. allowSingleDateInRange는 type prop이 range가 아닐 때 무시돼요.

import { useState } from 'react';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  const [value, setValue] = useState<[Date | null, Date | null]>([null, null]);
  return <MonthPicker type="range" allowSingleDateInRange value={value} onChange={setValue} />;
}

사전 설정 (Presets)

presets prop으로 커스텀 월 사전 설정을 추가할 수 있어요. 사전 설정은 캘린더 옆에 표시돼요.

import dayjs from 'dayjs';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  return (
    <MonthPicker
      presets={[
        { label: 'This month', date: new Date() },
        { label: 'Next month', date: dayjs().add(1, 'month').toDate() },
        { label: 'Last month', date: dayjs().subtract(1, 'month').toDate() },
        { label: 'In 6 months', date: dayjs().add(6, 'month').toDate() },
        { label: 'Next year', date: dayjs().add(1, 'year').toDate() },
        { label: 'Last year', date: dayjs().subtract(1, 'year').toDate() },
      ]}
    />
  );
}

type="range"와 함께 presets를 사용하려면 값을 두 날짜의 튜플로 정의해요.

import dayjs from 'dayjs';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  const today = dayjs();

  return (
    <MonthPicker
      type="range"
      presets={[
        { label: 'Last 3 months', date: [today.subtract(3, 'month').toDate(), today.toDate()] },
        { label: 'Last 6 months', date: [today.subtract(6, 'month').toDate(), today.toDate()] },
        { label: 'This year', date: [today.startOf('year').toDate(), today.endOf('year').toDate()] },
        { label: 'Last year', date: [today.subtract(1, 'year').startOf('year').toDate(), today.subtract(1, 'year').endOf('year').toDate()] },
      ]}
    />
  );
}

기본 날짜 (Default date)

defaultDate prop으로 처음에 어떤 연을 표시할지 결정하는 날짜 값을 설정할 수 있어요. 예를 들어 2015 연을 표시하려면 defaultDate={new Date(2015, 1)}을 설정해요. 값을 지정하지 않으면 defaultDate는 new Date()를 사용해요. 제공된 날짜 객체에서 월, 일, 분, 초는 무시되고 연만 사용돼요. 어떤 날짜 값이든 지정할 수 있어요.

date prop을 설정하면 defaultDate 값은 무시된다는 점에 주의해요.

import { useState } from 'react';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  const [value, setValue] = useState<Date | null>(null);
  return <MonthPicker defaultDate={new Date(2015, 1)} value={value} onChange={setValue} />;
}

제어된 날짜 (Controlled date)

date와 onDateChange props를 설정하면 현재 표시되는 연과 십년(decade)을 제어할 수 있어요. 이렇게 하면 날짜 선택 경험을 커스터마이즈할 수 있어요. 예를 들어 사용자가 범위에서 첫 날짜를 선택하면 현재 날짜 값에 한 해를 더할 수 있어요.

import dayjs from 'dayjs';
import { useState } from 'react';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  const [value, setValue] = useState<[string | null, string | null]>([null, null]);
  const [date, setDate] = useState(dayjs().format('YYYY-MM-DD'));

  const handleChange = (val: [string | null, string | null]) => {
    if (val[0] !== null && val[1] === null) {
      setDate((current) => dayjs(current).add(1, 'year').format('YYYY-MM-DD'));
    }

    setValue(val);
  };

  return <MonthPicker type="range" date={date} onDateChange={setDate} value={value} onChange={handleChange} />;
}

최소·최대 날짜 (Min and max date)

minDate와 maxDate props로 최소·최대 날짜를 정의할 수 있어요. 이전/다음 페이지를 사용할 수 없으면 해당 컨트롤이 비활성화돼요.

import { useState } from 'react';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  const [value, setValue] = useState<Date | null>(null);
  return <MonthPicker minDate={new Date('2022-01-01')} maxDate={new Date('2022-12-31')} value={value} onChange={setValue} />;
}

연·월 컨트롤에 props 추가 (Add props to year and month control)

getYearControlProps와 getMonthControlProps 함수로 연·월 컨트롤에 props를 추가할 수 있어요. 두 함수 모두 날짜를 단일 인자로 받아요. 함수에서 반환된 props가 연/월 컨트롤에 추가돼요. 예를 들어 특정 컨트롤을 비활성화하거나 스타일을 추가하는 데 사용할 수 있어요.

import dayjs from 'dayjs';
import { useState } from 'react';
import { MonthPicker, MonthPickerProps } from '@mantine/dates';

const getYearControlProps: MonthPickerProps['getYearControlProps'] = (date) => {
  if (dayjs(date).year() === new Date().getFullYear()) {
    return { style: { color: 'var(--mantine-color-blue-filled)', fontWeight: 700 } };
  }

  if (dayjs(date).year() === new Date().getFullYear() + 1) {
    return { disabled: true };
  }

  return {};
};

const getMonthControlProps: MonthPickerProps['getMonthControlProps'] = (date) => {
  if (dayjs(date).month() === 1) {
    return { style: { color: 'var(--mantine-color-blue-filled)', fontWeight: 700 } };
  }

  if (dayjs(date).month() === 5) {
    return { disabled: true };
  }

  return {};
};

열 수 (Number of columns)

numberOfColumns prop을 설정해 나란히 렌더링할 피커 수를 정의할 수 있어요.

import { useState } from 'react';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  const [value, setValue] = useState<[Date | null, Date | null]>([null, null]);
  return <MonthPicker type="range" numberOfColumns={2} value={value} onChange={setValue} />;
}

최대 레벨 (Max level)

사용자가 십년(decade) 레벨로 가는 것을 막으려면 maxLevel="year"을 설정해요.

import { MonthPicker } from '@mantine/dates';

function Demo() {
  return <MonthPicker maxLevel="year" />;
}

전체 너비 (Full width)

fullWidth prop을 설정하면 월 피커가 부모 컨테이너 너비의 100%를 채우도록 늘어나요.

import { useState } from 'react';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  const [value, setValue] = useState<Date | null>(null);
  return <MonthPicker fullWidth value={value} onChange={setValue} />;
}

크기 (Size)

import dayjs from 'dayjs';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  return <MonthPicker size="lg" />;
}

연·월 컨트롤 형식 변경 (Change year and months controls format)

yearsListFormat과 monthsListFormat props를 사용해 연/월 컨트롤의 dayjs format을 바꿀 수 있어요.

import { MonthPicker } from '@mantine/dates';

function Demo() {
  return <MonthPicker yearsListFormat="YY" monthsListFormat="MM" />;
}

라벨 형식 변경 (Change label format)

decadeLabelFormat과 yearLabelFormat을 사용해 십년(decade)/연 라벨의 dayjs format을 바꿀 수 있어요.

import { useState } from 'react';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  const [value, setValue] = useState<Date | null>(null);
  return <MonthPicker yearLabelFormat="YYYY year" value={value} onChange={setValue} />;
}

로컬라이제이션 (Localization)

보통은 DatesProvider에서 @mantine/dates 패키지의 locale을 지정하는 것이 낫지만, 컴포넌트별로 locale을 덮어쓸 수도 있어요.

import 'dayjs/locale/ru';
import { MonthPicker } from '@mantine/dates';

function Demo() {
  return <MonthPicker locale="ru" />;
}

네이티브 레벨 선택 (Native level select)

withNativeLevelSelect prop을 설정하면 캘린더 헤더의 레벨 버튼을 네이티브 select 요소로 바꿔요.

import { MonthPicker } from '@mantine/dates';

function Demo() {
  return <MonthPicker withNativeLevelSelect />;
}

접근성 (Accessibility)

ariaLabels prop으로 이전/다음 컨트롤의 aria-label 속성을 지정할 수 있어요.

import { MonthPicker } from '@mantine/dates';

function Demo() {
  return (
    <MonthPicker
      ariaLabels={{
        nextDecade: 'Next decade',
        previousDecade: 'Previous decade',
      }}
    />
  );
}

getYearControlProps/getMonthControlProps를 사용해 aria-label 속성을 커스터마이즈할 수 있어요.

import { MonthPicker } from '@mantine/dates';

function Demo() {
  return (
    <MonthPicker
      getYearControlProps={(date) => ({
        'aria-label': `Select year ${date.getFullYear()}`,
      })}
      getMonthControlProps={(date) => ({
        'aria-label': `Select month ${date.getFullYear()}/${date.getMonth()}`,
      })}
    />
  );
}

다음 이벤트는 포커스가 월 컨트롤에 있을 때만 트리거된다는 점에 주의해요.

키 (Key) 설명 (Description)
ArrowRight 다음 비활성 월에 포커스를 둬요
ArrowLeft 이전 비활성 월에 포커스를 둬요
ArrowDown 같은 열의 다음 비활성 월에 포커스를 둬요
ArrowUp 같은 열의 이전 비활성 월에 포커스를 둬요

더 알아보기 (Learn more)