How can I adjust the monthly screen in 'react-native-calendars'

151 Views Asked by At

When moving from 'react-native-calendars' to the previous or next month, I'd like to calculate how many weeks that month is and set it to fill the screen according to the number of weeks.

I want to adjust the height of the week's compartment as shown in the picture below

like this

Please tell me how to get a new weekly height and display it on the screen when you move to the previous month or the next month. ;(

[react-native-calendars](https://github.com/wix/react-native-calendars)

The problem with the current code is to set the weekly height for all months based on the current month.

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

function CalendarScreen() {
  // Get the height and width of the smartphone screen
  const { height, width } = Dimensions.get("window");

  // Calculate the number of weeks in the current month
  const today = new Date();
  // const today = new Date(2023, 7, 1);
  const year = today.getFullYear();
  const month = today.getMonth() + 1;

  // Calculate the first and last day of the current month
  const lastDay = new Date(year, month, 0).getDate();
  const firstDayOfWeek = new Date(year, month - 1, 1).getDay();
  const lastDayOfWeek = new Date(year, month - 1, lastDay).getDay();

  // Calculate the number of weeks in the current month
  let totalWeeks = 0;

  for (let day = 1; day <= lastDay; day++) {
    if ((day + firstDayOfWeek - 1) % 7 === firstDayOfWeek) {
      console.log(`Days with the same weekday: ${day}th day`);
      totalWeeks += 1;
    }
  }
  if (lastDayOfWeek < firstDayOfWeek) {
    totalWeeks += 1;
  }

  console.log(`Today is: ${today}`);
  console.log(`The first day of this month is: ${firstDayOfWeek}`);
  console.log(`The last day of this month is: ${lastDayOfWeek}`);
  console.log(`Total weeks in this month: ${totalWeeks} weeks!`);
  const calendarHeight = height * 0.9;

  return (
    <View>
      <Text>Calendar</Text>
      <View style={{ height: calendarHeight }}>
        <Calendar
          style={{ height: "100%" }}
          theme={{
            // Set the height of a calendar cell
            "stylesheet.day.basic": {
              base: {
                // Adjust cell height for 4/5/6 weeks
                height: calendarHeight / (totalWeeks + 1.2), //temp
              },
            },
          }}
        />
      </View>
    </View>
  );
}

export default CalendarScreen;

0

There are 0 best solutions below