作記録

記憶代わり

Typescriptのカレンダーモジュール

結論

ts-calendar という Typescriptのカレンダーモジュールを作って npm に公開しました。

www.npmjs.com

経緯

ライブラリを使うと Tailwind CSS と相性が悪かったり、やりたい事出来なそうな感じだったので自身で実装しました。

使用方法

github.com

Reactでの利用例

Reactでは下記のように使う想定でおります。

import React, {useState} from 'react';
import Calendar from 'ts-calendar/lib/model/calendar/Calendar';
import CalendarWeek from 'ts-calendar/lib/model/calendar/CalendarWeek';

const App = () => {
  const [calendar, setCalendar] = useState<Calendar>(Calendar.ofThisMonth);

  const nextMonth = () => {
    setCalendar(calendar.nextMonth());
  }

  const lastMonth = () => {
    setCalendar(calendar.lastMonth());
  }

  return (
    <>
      <div>
        <table>
          <thead>
          <tr>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
          </tr>
          </thead>
          <tbody>
          {calendar.getWeeks().map((week: CalendarWeek, index: number) => {
            return (
              <tr key={index}>
                {week.getDates().map(date => {
                  return (
                    <td key={date.toString()}>
                      {calendar.isThisMonth(date.toMonth()) ? (
                        <>{ date.toNumber() }</>
                      ) : (
                        <></>
                      )}
                    </td>
                  )
                })}
              </tr>
            )
          })}
          </tbody>
        </table>
      </div>
    </>
  );
}

export default App;