LoginSignup
4
4

More than 3 years have passed since last update.

React-Calendarで超簡単にカレンダーを作ってみた

Posted at

会社のイベントとして、2020年のアドベントカレンダーで記事を書いたのですが、個人のQiitaでも同じものを公開したいな〜と思ったので、ちょっとだけ変えて公開します!

去年の案件で急にReactでカレンダーを作ることになり、有識者もいない中、四苦八苦したのですが、ライブラリって便利だな〜と感じたので、Reactのreact-calendarを使ってカレンダーを作成したときのことを書きます。

※環境構築とかは端折ります。

react-calendarとは

カレンダー実装だともっとメジャーなライブラリがあるかも知れないんのですが、今回、私はreact-calendarを使ってみたのですが、簡単にReactでカレンダーを実装できちゃいました。

条件を絞って、日付ごとに任意の内容を表示させたり、スタイルのカスタマイズなど 柔軟に対応できます。

公式:react-calendar

react-calendarで実装してみる

react-calendarをインストール

yarnで「react-calendar」をインストールします。

yarn add react-calendar

react-calendarをimportする

react-calendarをimportしてCalendarコンポーネントを呼び出します。

CalenderCmponent.jsx

import Calendar from 'react-calendar'

export default class Calendar extends Component {

    render() {
        return(
            <Calendar />
        )
    } 
}

これだとまだ動きません!

カレンダーに日付を表示する

カレンダーのタイルに日付(日本時間)を表示します。

CalenderCmponent.jsx
import Calendar from 'react-calendar'

export default class Calendar extends Component {

    render() {
        return(
            <div>
                <Calendar
                    locale="ja-JP"
                    value={this.state.date}
                 />
          </div>
        )
    } 
}

それぞれのPropsについては公式だと以下のように説明されています。(英語のドキュメントのみ、、、)

Description Description Default value Example values
locale Locale that should be used by the calendar. Can be any IETF language tag. User's browser settings "hu-HU"
value Calendar value. Can be either one value or an array of two values. If you wish to use React-Calendar in an uncontrolled way, use defaultValue instead. "n/a" ・Date: new Date()
・An array of dates: [new Date(2017, 0, 1), new Date(2017, 7, 1)]

これで、カレンダーの作成は完了です。とても簡単!!

カレンダーに任意のアイテムを表示してみる

これだけだと寂しいので、日付タイルに任意のアイテムを表示させてみたいと思います。

CalenderCmponent.jsx
import Calendar from 'react-calendar'

export default class Calendar extends Component {

    constructor(props) {
        super(props);
        this.state = {
            date: new Date(),
            //テストデータ
            month_item: {
                2020-12-01: { text: 'work' },
                2020-12-10: { text: 'hangout' },
                2020-12-24: { text: 'Christmas Eve' },
                2020-12-25: { text: 'Christmas' },
            }
        }
    };


     //日付の内容を出力
      getTileContent({ date, view }) {
          if (view === 'month') {
              const targetDate = moment(date).format('YYYY-MM-DD')

             return   month_item[targetDate] && month_item[targetDate].text ?
                 <div>
                        <p>{month_item[targetDate].text}</p>
                 </div>
               : null

          }
      }


    render() {
        return(
            <div>
                <Calendar
                    locale="ja-JP"
                    value={this.state.date}
                    tileContent={this.getTileContent.bind(this)} //ここを追加
                 />
    </div>
        )
    } 
}

tileContentの詳細の説明は以下です。functionを呼び出して、returnされたものを渡せば任意の日付に内容を表示させることができます。

Description Description Default value Example values
tileContent Allows to render custom content within a given calendar item (day on month view, month on year view and so on). n/a ・String: "Sample"
・React element:
・Function: ({ activeStartDate, date, view }) => view === 'month' && date.getDay() === 0 ? It's Sunday! : null

まとめ

Reactって便利〜! 今回の記事では説明していませんが、Reduxと合わせてDBからデータを引っ張ってきてstateで制御すれば、スケジュールを登録したり、表示させたりすることも可能でした!

今回記載している以外にもたくさんPropsの種類もあるので、気になる方はぜひ公式URLから見てみてください!

参考

React-Calendar が便利 | バシャログ。
Reactでカレンダー作成(React-Calendarライブラリ)

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4