🍣

ReactNativeでカレンダーを表示する方法

2024/12/09に公開

はじめに

React Nativeでは、react-native-calendarsライブラリを使うことで簡単にカレンダーを実装できます。
以下では、カレンダーを表示し、ユーザーが選択した日付をハイライトして表示する方法を詳しく説明します。

必要なライブラリのインストール

react-native-calendarsをインストールします。

npm install react-native-calendars

または、yarnを使用している場合は:

yarn add react-native-calendars

ソースコード

import React, { useState } from "react";
import { View, Text, StyleSheet } from "react-native";
import { Calendar } from "react-native-calendars";

export default function CalendarScreen() {
  const [selectedDate, setSelectedDate] = useState<string | null>(null);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>カレンダー</Text>

      {/* カレンダー表示 */}
      <Calendar
        onDayPress={(day) => setSelectedDate(day.dateString)} 
        markedDates={
          selectedDate
            ? { [selectedDate]: { selected: true, marked: true } } 
            : {}
        }
        theme={{
          selectedDayBackgroundColor: "#00adf5", 
          todayTextColor: "#00adf5", 
        }}
      />

      {/* 選択された日付の表示 */}
      <Text style={styles.selectedDate}>
        選択された日付: {selectedDate || "なし"}
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
    backgroundColor: "#fff",
  },
  title: {
    fontSize: 24,
    fontWeight: "bold",
    marginBottom: 16,
    textAlign: "center",
  },
  selectedDate: {
    fontSize: 18,
    marginTop: 16,
    textAlign: "center",
  },
});

ポイントとなるソース

以下は、カレンダーの表示と日付の選択処理の重要な部分です。

<Calendar
  onDayPress={(day) => setSelectedDate(day.dateString)} // 日付選択時に状態を更新
  markedDates={
    selectedDate
      ? { [selectedDate]: { selected: true, marked: true } }
      : {}
  }
  theme={{
    selectedDayBackgroundColor: "#00adf5", // 選択された日付の背景色
    todayTextColor: "#00adf5",            // 今日の日付の色
  }}
/>

動作の流れ

  1. 日付の選択
    ユーザーが日付を選択すると、onDayPressが発火し、selectedDateが更新されます。

  2. markedDatesの再計算
    markedDatesの値が再計算され、selectedDateをキーとするオブジェクトが動的に生成されます。

  3. カレンダーの更新
    カレンダーはmarkedDatesの情報に基づいて選択された日付をハイライトします。

{
  "2023-12-01": { selected: true, marked: true }
}

実際の画面

まとめ

この方法を応用すれば、カレンダー上で特定の日付にイベントや予定を表示するなど、さらなる機能拡張も可能です。興味があれば、ぜひ試してみてください

Discussion