react-big-calendarの攻略
イベントカレンダー機能
Reactで作ったCMSにカレンダー機能を実装しました。
動作イメージ
カレンダー機能をリリースしました! pic.twitter.com/uY5j3YkkCV
— キャップ野球情報局 (@cap_bb_info) December 22, 2019
使ったライブラリ
アジェンダテーブル
theaderとtbodyが連動していないため、OSSに初めてプルリクを出してみました。 とりあえず応急措置としてスタイルで固定で横幅を指定します。
th.rbc-header:nth-child(1){ min-width: 77px; } th.rbc-header:nth-child(2){ min-width: 121px; } th.rbc-header:nth-child(3){ width: 100%; }
表示の日本語化
import globalize from "globalize"; require("./globalize.ja.js"); const localizer = globalizeLocalizer(globalize);
localizerはreact-big-calendarにpropsとして渡します。
ツールバーの日本語化
こちらはglobalizeに対応していないハードコーディングなので、 CSSで元の文字を0pxにし、要素を増やす形で置き換えます。
/*文字置き換え*/ .rbc-btn-group > button{ font-size: 0px; } .rbc-btn-group:nth-child(1) > button:nth-child(1)::before{ font-size: 14px; content: '今日'; } .rbc-btn-group:nth-child(1) > button:nth-child(2)::before{ font-size: 14px; content: '←'; } .rbc-btn-group:nth-child(1) > button:nth-child(3)::before{ font-size: 14px; content: '→'; } .rbc-btn-group:nth-child(3) > button:nth-child(1)::before{ font-size: 14px; content: '月'; } .rbc-btn-group:nth-child(3) > button:nth-child(2)::before{ font-size: 14px; content: '週'; } .rbc-btn-group:nth-child(3) > button:nth-child(3)::before{ font-size: 14px; content: '日'; } .rbc-btn-group:nth-child(3) > button:nth-child(4)::before{ font-size: 14px; content: 'スケジュール'; }
props
components
event(月・週・日で表示されるコンポーネント)とagenda(スケジュールで表示されるイベント)の動作を記述できる。
Event = ({ event }) => { return ( <span> {event.title} </span>); }; EventAgenda = ({ event }) => { return ( <div onClick={()=>{ this.setState({ isOpen:true, selectEvent:event }) }} > {event.type}/{event.title} </div> ); }; components={{ event: this.Event, agenda: { event: this.EventAgenda } }}
onSelectEvent
agendaで表示されるコンポーネントが選択されたときに発火するイベント (ここではポップアップモーダルを開く)
onSelectEvent={(event,e)=>{ this.setState({ isOpen:true, selectEvent:event }) }}
eventPropGetter
event.typeによってスタイルを変える処理 参考:Change color of react-big-calendar events
eventPropGetter={(event, start, end, isSelected) => { let bgColor; let fontColor; switch (event.type) { case "練習会": bgColor = "#BF7A87"; fontColor = "aliceblue"; break; default: bgColor = "#386537"; fontColor = "aliceblue"; break; } let newStyle = { backgroundColor: bgColor, color: fontColor }; return { className: "", style: newStyle }; }}