Reactで簡易的なカレンダーを作成
2025/01/31 (金) - 09:00 JavaScript
Reactを使用して簡易的なカレンダーを作成しました。デフォルトでは今月のカレンダーを表示、前月と次月のボタンを押下することで月表示を切り替えることができます。実装環境は以下の通り。
- React 19.0.x
- Vite 5.x
予めプロジェクトを立ち上げておき、App.jsx
に以下のように記述します。前月、次月のボタンを押下した際にuseState
でカレンダーの表示を切り替える仕組みです。
import { useState } from 'react'
import './App.css'
const App = () => {
const [currentDate, setCurrentDate] = useState(new Date());
const getDaysInMonth = (year, month) => {
return new Date(year, month + 1, 0).getDate();
};
const getFirstDayOfMonth = (year, month) => {
return new Date(year, month, 1).getDay();
};
const renderCalendar = () => {
const year = currentDate.getFullYear();
const month = currentDate.getMonth();
const daysInMonth = getDaysInMonth(year, month);
const firstDayOfMonth = getFirstDayOfMonth(year, month);
const blanks = Array(firstDayOfMonth).fill(null);
const daysArray = Array.from({ length: daysInMonth }, (_, i) => i + 1);
const allDays = [...blanks, ...daysArray];
const totalCells = Math.ceil(allDays.length / 7) * 7;
const remainingBlanks = totalCells - allDays.length;
allDays.push(...Array(remainingBlanks).fill(null));
const weeks = [];
let week = [];
allDays.forEach((day, index) => {
week.push(day);
if ((index + 1) % 7 === 0) {
weeks.push(week);
week = [];
}
});
return weeks.map((week, weekIndex) => (
<tr key={weekIndex}>
{week.map((day, dayIndex) => {
const dayOfWeek = (firstDayOfMonth + dayIndex) % 7;
return (
<td key={dayIndex}>
{day || ''}
</td>
);
})}
</tr>
));
};
const goToPreviousMonth = () => {
setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1));
};
const goToNextMonth = () => {
setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1));
};
return (
<div className="calendar">
<div className="calendar-header">
<button onClick={goToPreviousMonth}>前の月</button>
<h2>
<span className="calendar-year">{currentDate.getFullYear()}年</span>
<span className="calendar-month">{currentDate.toLocaleString('default', { month: 'long' })}</span>
</h2>
<button onClick={goToNextMonth}>次の月</button>
</div>
<table>
<thead>
<tr>
<th>日</th>
<th>月</th>
<th>火</th>
<th>水</th>
<th>木</th>
<th>金</th>
<th>土</th>
</tr>
</thead>
<tbody>{renderCalendar()}</tbody>
</table>
</div>
);
};
export default App;
市販の一般的なカレンダーに習い、日曜日を開始としてtd要素で並べます。今回日曜日を赤文字・土曜日を青文字としたかったので、こちらはCSSのセレクタを用いて色変更を行いました。
table{
width: 100%;
border-collapse: collapse;
table-layout: fixed;
}
th,
td{
padding: 10px;
border: 1px solid #ccc;
text-align: center;
vertical-align: middle;
}
th:first-child,
td:first-child{
color: red;
}
th:last-child,
td:last-child{
color: blue;
}
細かいスタイルの反映については個別に適宜実装ください。
おしまい♥
タグ:React
おすすめ記事
- clipboard.writeTextでクリップボードにテキストをコピーするときはhttpsで行う
- JavaScript(VanillaJS)でDOM要素を指定するには
- Next.js App Routerによるhead要素内の設定(meta OGPとかfavicon)
- PokeAPIとJavaScriptで日本語のポケモン情報をゲットする
- Web Speech APIを使ってブラウザでテキストを読み上げる
トラックバック & ピンバック
- この記事へのトラックバックURI:
- https://weblog.walk-life.me/react_easy_calendar/trackback/