Giter VIP home page Giter VIP logo

acro5piano / react-native-big-calendar Goto Github PK

View Code? Open in Web Editor NEW
397.0 9.0 134.0 9.42 MB

gcal/outlook like calendar component for React Native

Home Page: https://react-native-big-calendar.vercel.app

License: MIT License

JavaScript 1.34% TypeScript 91.50% Java 4.10% Ruby 1.31% Objective-C 1.32% Objective-C++ 0.43%
react react-native react-native-web cross-platform calendar calendar-view calendar-component

react-native-big-calendar's Introduction

test release npm version

react-native-big-calendar

Cross-platform gcal/outlook like calendar component for React Native.

⚠️ Help me to debug this component ⚠️

It's a hard task to debug this library on three platforms. I usually develop with the Web version first, then confirm its functionality with real devices. My PC is Linux and my phone is Android, so on Android it is easy to test, but to debug on iOS, I have to bring my Macbook Pro from my garage and connect my wife's iPhone and test it. Every time I launch my MacBook Pro, it requires updating Xcode or even performing a full system update.. It takes so long time to start debug. As React Native works on iOS better than Android, I always sometimes skip testing it, so there should be a bug on iOS. If you help me debug it, I would much appreciate!

Components Demo

Features

  • Cross Platform: Runs on the Web, iOS, Android with the power of React
  • Type-safe: Fully written in TypeScript
  • Customizable: Able to provide your own theme, and pass your component to render.
  • Lightweight: ~9KB (min + gzip), dependency is dayjs and calendarize

Install

npm install --save react-native-big-calendar

Or if you use Yarn:

yarn add react-native-big-calendar

Other dependencies

Please ensure peer dependencies are installed.

npm install react react-native

TypeScript

If you use TypeScript ensure @types/react and @types/react-native is installed. react-native-big-calendar internally uses them.

npm install --save-dev @types/react @types/react-native

Usage on the Web

If you are using this module on the Web, please install react-native-web.

npm install react-native-web

If you are using Create React App, you are ready to go 🎉

For more details, please refer to the official react-native-web installation guide.

https://github.com/necolas/react-native-web

Getting Started

import { Calendar } from 'react-native-big-calendar'

const events = [
  {
    title: 'Meeting',
    start: new Date(2020, 1, 11, 10, 0),
    end: new Date(2020, 1, 11, 10, 30),
  },
  {
    title: 'Coffee break',
    start: new Date(2020, 1, 11, 15, 45),
    end: new Date(2020, 1, 11, 16, 30),
  },
]

function App() {
  return <Calendar events={events} height={600} />
}

API Documentation

Summary

export interface CalendarProps<T extends ICalendarEventBase> {
  events: T
  height: number
  overlapOffset?: number
  hourRowHeight?: number
  ampm?: boolean
  date?: Date
  eventCellStyle?: EventCellStyle<T>
  eventCellTextColor?: string
  allDayEventCellStyle?: allDayEventCellStyle<>
  allDayEventCellTextColor?: string
  calendarContainerStyle?: ViewStyle
  headerContainerStyle?: ViewStyle
  bodyContainerStyle?: ViewStyle
  renderEvent?: (
    event: T,
    touchableOpacityProps: CalendarTouchableOpacityProps,
  ) => ReactElement | null
  renderHeader?: React.ComponentType<CalendarHeaderProps<T> & { mode: Mode }>
  renderHeaderForMonthView?: React.ComponentType<CalendarHeaderForMonthViewProps>
  locale?: string
  hideNowIndicator?: boolean
  mode?: Mode
  scrollOffsetMinutes?: number
  showTime?: boolean
  swipeEnabled?: boolean
  weekStartsOn?: WeekNum
  weekEndsOn?: WeekNum
  onChangeDate?: DateRangeHandler
  onPressCell?: (date: Date) => void
  onPressDateHeader?: (date: Date) => void
  onPressEvent?: (event: ICalendarEvent<T>) => void
  eventMinHeightForMonthView?: number
  activeDate?: Date
  moreLabel?: string
  showAdjacentMonths?: boolean
  sortedMonthView?: boolean
  showVerticalScrollIndicator?: boolean
}

<Calendar /> Props are:

name required type description
events yes ICalendarEvent<T>[] The events which will be rendered on the calendar. You can extend the type ICalendarEvent by providing a value to generic type T (see ./stories/events.tsx for an example). with optional children to display custom components inside the event, and optional event renderer function to take complete control over the rendered event (advanced feature). Events occurring during the same time range will be layered, offset, and assigned a unique color.
height yes number Calendar height.
hideNowIndicator no boolean Hides the indicator for the current time. By default the now indicator is shown.
hourRowHeight no number Hour row height
onPressEvent no (event: ICalendarEvent<T>) => void Event handler which will be fired when the user clicks an event.
onChangeDate no ([start: Date, end: Date]) => void Event handler which will be fired when the current date range changed.
onPressCell no (date: Date) => void Event handler which will be fired when the current date cell is clicked. The minute set to 0.
onLongPressCell no (date: Date) => void Same as above but triggered by a long press.
onPressDateHeader no (date: Date) => void Event handler which will be fired when the user clicks a date from the header.
mode no 'month' | 'week' | '3days' | 'day' | 'schedule' | 'custom'
eventCellStyle no ViewStyle | (event: ICalendarEvent<T>) => ViewStyle The style of Event cell. Accepts either style object (static) or function (dynamic).
eventCellTextColor no string The color of Event cell text.
allDayEventCellStyle no ViewStyle | (event: ICalendarEvent<T>) => ViewStyle The style of all day Event cell. Accepts either style object (static) or function (dynamic).
allDayEventCellTextColor no string The color of all day Event cell text.
headerContentStyle no ViewStyle The style of the Header's content. Accepts a style object (static).
dayHeaderStyle no ViewStyle The style of the Header's day numbers. Accepts a style object (static).
dayHeaderHighlightColor no string The style of the Header's highlighted day number. Accepts a style object (static).
weekDayHeaderHighlightColor no string The style of the Header's highlighted week day. Accepts a style object (static).
scrollOffsetMinutes no number Scroll to specific minutes in a day. e.g.) set 480 to scroll to 8am when the calendar rendered.
date no Date Initial date of calendar. Defaults to new Date (current time).
onSwipeEnd no (date: Date) => void Event handler which will be fired when swiping left or right. Memoize your function to prevent unnecesary re-renders
swipeEnabled no boolean
showTime no boolean
ampm no boolean Use 12 hours time format instead of 24 hours.
weekStartsOn no 0 | 1 | 2 | 3 | 4 | 5 | 6 Which day the week starts on. Sunday is 0.
weekEndsOn no 0 | 1 | 2 | 3 | 4 | 5 | 6 Which day the week ends on. Sunday is 0.
locale no string Custom locale. See I18n section
overlapOffset no number Adjusts the indentation of events that occur during the same time period. Defaults to 20 on web and 8 on mobile.
isRTL no boolean Switches the direction of the layout for use with RTL languages. Defaults to false.
renderEvent no EventRenderer Custom event renderer. See the type definition below.
renderHeader no HeaderRenderer Custom header renderer.
eventMinHeightForMonthView no number Minimun height for events in month view. Should match the min-height of your custom events. Defaults to 22.
activeDate no Date Date highlighted in header. Defaults to today (current time).
headerComponent no ReactElement Calendar body header component.
headerComponentStyle no ViewStyle Calendar body header component wrapper styling. Accepts a style object (static)
hourStyle no TextStyle Calendar body hours styling. Accepts a style object (static)
showAllDayEventCell no boolean Boolean for showing/hiding the all day event cell
moreLabel no string String to replace More label in month view. Default: '{moreCount} More'. {moreCount} is replaced by number of extra events
showAdjacentMonths no boolean Boolean for showing/hiding adjacent months in month view. Defaults to true
sortedMonthView no boolean (for performance) Boolean for sorting events in month view. Defaults to true
isEventOrderingEnabled no boolean (for performance) Boolean for sorting events in all view. Defaults to true
renderCustomDateForMonth no boolean Custom renderer for Date Cell
disableMonthEventCellPress no boolean Prevent Month view event cells from being pressed. Defaults to false
itemSeparatorComponent no ReactElement React Component for separate items in schedule mode. but not at the top or bottom. Refer React Native FlatList ItemSeparatorComponent for more info.
enrichedEventsByDate no Record<string, T[] (for performanace) Enriched events dictionary that will be used instead of building it inside the library.
enableEnrichedEvents no boolean (for performance) Boolean for enabling enrichedEvents logic. Defaults to false
eventsAreSorted no boolean (for performance) Boolean for skip sorting the events inside the library due they are already sorted. Defaults to false
showWeekNumber no boolean Show week number. Week number will be shown at top left corner for week/day mode and at start of each row for month mode
weekNumberPrefix no string Prefix for week number. For month mode, the prefix will be shown in header row.

EventRenderer

type EventRenderer<T> = (
  event: ICalendarEvent<T>,
  touchableOpacityProps: CalendarTouchableOpacityProps,
) => ReactElement | null

For more information, see Storybook

ICalendarEventBase

interface ICalendarEventBase {
  start: Date
  end: Date
  title: string
  children?: ReactElement | null
  disabled?: boolean
}

All day events

All day events should start and end on 0 in hour, minutes, and seconds (T00:00:00). For example:

{
    title: 'all day event',
    start: "2021-12-24T00:00:00.000Z",
    end: "2021-12-24T00:00:00.000Z", // same date as `start`
}

Using a custom event render function

You can specify custom event render function which receives the calculated TouchableOpacity prop and event.

  • The function renderEvent must return a ReactElement.
  • The component should be wrapped inside a TouchableOpacity or any DOM element which accepts positioning and click events (onPress, ...).
export interface MyCustomEventType {
  color: string
}

const renderEvent = <T extends ICalendarEventBase>(
  event: T,
  touchableOpacityProps: CalendarTouchableOpacityProps,
) => (
  <TouchableOpacity {...touchableOpacityProps}>
    <Text>{`My custom event: ${event.title} with a color: ${event.color}`}</Text>
  </TouchableOpacity>
)

<Calendar renderEvent={renderEvent} />

Displaying event's notes

Your events can contain a prop children An example can be found here.

const eventNotes = useMemo(
  () => (
    <View style={{ marginTop: 3 }}>
      <Text style={{ fontSize: 10, color: 'white' }}> Phone number: 555-123-4567 </Text>
      <Text style={{ fontSize: 10, color: 'white' }}> Arrive 15 minutes early </Text>
    </View>
  ),
  [],
)

export const myEvents: ICalendarEventBase[] = [
  {
    title: 'Custom reminder',
    start: dayjs().set('hour', 16).set('minute', 0).toDate(),
    end: dayjs().set('hour', 17).set('minute', 0).toDate(),
    children: eventNotes,
  },
]

Theme

You can customize the calendar by passing the theme prop. theme should be like this interface partially:

export interface Palette {
  main: string
  contrastText: string
}

export type Typography = Pick<
  TextStyle,
  'fontFamily' | 'fontWeight' | 'fontSize' | 'lineHeight' | 'letterSpacing' | 'textAlign'
>

export interface ThemeInterface {
  palette: {
    primary: Palette
    nowIndicator: string
    gray: {
      100: string
      200: string
      300: string
      500: string
      800: string
    }
    moreLabel: string
  }
  isRTL: boolean
  typography: {
    fontFamily?: string
    xs: Typography
    sm: Typography
    xl: Typography
    moreLabel: Typography
  }
  eventCellOverlappings: readonly Palette[]
  moreLabel: TextStyle
}

For example:

const darkTheme = {
  palette: {
    primary: {
      main: '#6185d0',
      contrastText: '#000',
    },
    gray: {
      '100': '#333',
      '200': '#666',
      '300': '#888',
      '500': '#aaa',
      '800': '#ccc',
    },
  },
}

<Calendar
  height={SCREEN_HEIGHT}
  theme={darkTheme}
/>

I18n

Please specity your locale via locale prop and import day.js locale file:

import 'dayjs/locale/ja'

<Calendar
  locale="ja"
  {/* ... */}
/>

You can find your dayjs locale here:

https://github.com/iamkun/dayjs/tree/dev/src/locale

Enriched Events Logic (Performance Boost)

Performant Data Structure

We create and cache a dictionary keyed by date with all the events properties plus the overlapping counting:

{
    [YYYY-MM-DD]: [
        {
            ...all event information,
            overlapPosition: int
            overlapCount: int
        }
    ]
}

Multi-days events

When an event spans multiple days, we create a new event for each day it spans. For example, an event that starts on 2021-05-01 and ends on 2021-05-03 will be represented as 3 events, one for each day with the following time props:

--- First day
2021-05-01: {
   ...other data
   start: event start datetime
   end: current day midnight
}
-- All the intermediate days:
2021-05-02: {
   ...other data
   start: previous day midnight
   end: current day midnight
}
-- Final day
2021-05-03: {
   ...other data
   start: previous day midnight
   end: event start datetime
}

Enriched Events Renderer

Optimised renderer get each event from the dictionary and render them without adding any extra logic like filtering or sorting.

Preprocessed Data

You can build the dictionary by yourself and send it to the library through the prop enrichedEventsByDate.

This is specially useful for example when you want to build the dictionary in a background job.

Running demo on a real device and develop

Setup

After checking this repo, please run:

yarn install
yarn sync-rndemo
cd rndemo
yarn install

Start

Start React Native development server in the demo directory:

cd rndemo
yarn start

Then, open another terminal and run:

# For ios
pod install
yarn ios

# For Android
yarn android

Every time you modify code of this library, you should run the following command in the root directory:

yarn sync-rndemo

Screenshots

Who's using this?

If you are using this library, please send a PR to add your organization!

Sponsors

Enterprise support

First, thank you for your interest in this project. As this library is getting famous, lots of people are requesting features they need. I would like to respond all of them as possible, but there are limited hours I'm working on this. To be a full-time open sourcer and make this project sustainable, I've decided to add the enterprise support.

Enterprise customers are able to obtain:

  • Full customization like colors, logos, images, and more.
  • Priority response and development.
  • Consultancy for React, TypeScript, and React Native application.

Note that some Enterprise features will be merged to the OSS version too.

If you are interested in those features, please send an email to: [email protected]

Hire me

I'm a freelance software engineer specialized in React, React Native and TypeScript. Also available for GraphQL and RDB backend, and Node.JS applications.

If you are interested in hiring me, please send an email to: [email protected]

I'm based in Japan (by the beautiful sea), so a remote contract job is especially welcome.

react-native-big-calendar's People

Contributors

acro5piano avatar akrueger90 avatar ashwinnagarro avatar changwoolab avatar charithamila avatar dependabot-preview[bot] avatar dependabot[bot] avatar fabrianibrahim avatar gilad-shnoor avatar jessekoper avatar kbwo avatar lespoir avatar letty avatar lorenzogatti avatar mindbodysolotestfirebase avatar mubashiralisiddiqui avatar offensivelybad avatar oportojca avatar pakile avatar quocvn avatar rajrohityadav avatar rkoningsdept avatar sebastienfi avatar shawnroller avatar sheena1234 avatar shubhamkashyap1601 avatar techsaq avatar titanve avatar wseow87 avatar yuan9090 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-big-calendar's Issues

Events spanning multiple days not rendering correct

Hello.

It seems like events only render of they have start date on a rendered date.

  1. If an event starts before rendered dates it will not render at all even if end date is past the whole span.
  2. If looking at multiple days a multi day event will only render on the "first" date.

Example 1. Day view. Only renders one of the events
image

Example 2. Three day view.

  • Event "50379" Should render on every single day since its start is long before and long after the entire span.
  • Event "50388" Renders correctly the first day but not at all on the other days even tough it has end date that is long past the 3 day span.
    image

Events not showing

Downloaded and ran your example:

import { Calendar } from 'react-native-big-calendar'

const events = [
  {
    title: 'Meeting',
    start: new Date(2020, 9, 23, 10, 0),
    end: new Date(2020, 9, 23, 10, 30),
  },
  {
    title: 'Coffee break',
    start: new Date(2020, 9, 24, 15, 45),
    end: new Date(2020, 9, 24, 16, 30),
  },
]

function App() {
  return <Calendar events={events} height={600} />
}

however no matter what I do/change, the calendar will show as empty without any events.

Wrong object type on BaseEvent

BaseEvent has start and end fields defined as Date.

The event onPressEvent from Calendar component emits a BaseEvent object.
That instance seems to have its start and end fields as DayJs objectes instead of date.

Cannot use eventRenderer with react-native and expo

Good morning.

Description

I'm trying to use the eventRenderer function in the events array but it doesn't work, would you please help me to know what I'm doing wrong? The main objective is to style the event cell individually (font-size by task time span).

Screencapture

image

image

Make sure object exists before using scrollTo method

Hi there,

First of all thanks a lot for creating and maintaining this repo, it has been really helpful! :)

That being said, I've encountered an issue when using the prop scrollOffsetMinutes:

Screen Shot 2021-03-08 at 3 50 31 pm

I think to fix that, it would only require to the following change (double checking the object exists before using the scrollTo method):

Screen Shot 2021-03-08 at 3 58 02 pm

Cheers

min and max time range

Related: #440

It would be great if min and max time range.

I'd like to ask you how the custom mode works and if it is possible to present hours as steps(30) and timeslots(1)? I've been using react big calendar for react, and it does have this amazing feature where I can say for instance that the initial hour is 06:30 and the last slot is 22:30 to be presented, and it renders 06:30, 07:00, 07:30, etc.

Proposal:

<Calendar
  minTime="06:30"
  maxTime="22:00"
/>

Issue with swiping left and right

Hey,
First, i would like to say that i love the lib and the work you have done here
There is a small problem i would like to address you with,

My goal is to swipe the dates correctly, meaning:
When i swipe my finger Left i want to it to advance in the dates forward and not render the previous ones
And to other side accordingly

Please if you dont understand something tell me

Adding a video:

Video to explain

Contributing Guide

Hello 🙂
I find the library very interesting, however it lacks some features that I would like to have as a "month" view, a "day" view or display an event when it lasts all day...
So I would like to know if it is possible for you to put a Contribution Guide in the README so that I can contribute to the development of the lib ?

Thank's 😉

'event' is not defined.

image

This is what I encountered with latest version.

This error is located at:
in NavigationContainer (at App.js:82)
in ThemeProvider (at App.js:81)
in Provider (at App.js:80)
in App (at renderApplication.js:45)
in RCTView (at AppContainer.js:109)
in RCTView (at AppContainer.js:135)
in AppContainer (at renderApplication.js:39)

Changing hours in day

Im trying to customise to use certain hours of the day (for example 9-5)

If i change the hours to reflect this. I can draw the grid etc fine

But rendering the current time and the events are not correct.

From my understanding, its due to the logic within the getRelativeTopInDay and getEventCellPositionStyle methods.

But i'm struggling to figure out the logic. Is there an easy way to make this universal based on the hours variable in utils.js?

Cell showing "More" multiple times

Simulator Screen Shot - iPhone 11 - 2021-06-10 at 16 38 50

Shouldn't it just be showing "5 more" and "7 more" once?

Here's my code

import React, { FunctionComponent, useMemo } from 'react';
import { ScrollView, Dimensions } from 'react-native';
import { Calendar, ICalendarEvent } from 'react-native-big-calendar';
import moment from 'moment';
import { useSelector } from 'react-redux';
import Navbar from '../commons/Navbar';
import { RootState } from '../../reducers';

const { height } = Dimensions.get('window');

const CalendarView: FunctionComponent = () => {
  const { appointments } = useSelector((state: RootState) => state.appointments);
  const events: ICalendarEvent[] = useMemo(() => {
    return appointments.map(a => {
      return { start: moment(a.Times.Start).toDate(), end: moment(a.Times.End).toDate(), title: a.Client.Forename };
    });
  }, [appointments]);
  return (
    <>
      <Navbar back />
      <ScrollView>
        <Calendar
          onPressCell={date => console.log(date)}
          onPressEvent={event => console.log(event)}
          events={events}
          height={height - 100}
          mode="month"
        />
      </ScrollView>
    </>
  );
};

export default CalendarView;

Cell Height?

Hi,
First of all thank you for such a great plugin.

Is it possible to change the height of the cell? I tried using eventcellstyle but it didnt work. Please advise.

Thank you.

Encountered two children with the same key

The key for event generated with the logic key={'${event.start}${event.title}'}. I have a case where there can be multiple events with exactly same details. This results in a react warning.

Maybe index be added to the combination to prevent this from happening?

Receiving TypeError: undefined

Running this lib for the first time and receiving this Type Error:

TypeError: undefined is not an object (evaluating '_$$_REQUIRE(_dependencyMap[14], "react-native-big-calendar").Calendar')

This error is located at:
    in Unknown (at SceneView.tsx:122)
    in StaticContainer
    in EnsureSingleNavigator (at SceneView.tsx:114)
    in SceneView (at useDescriptors.tsx:153)
    in RCTView (at View.js:34)
    in Unknown (at CardContainer.tsx:245)
    in RCTView (at View.js:34)
    in Unknown (at CardContainer.tsx:244)
    in RCTView (at View.js:34)
    in Unknown (at CardSheet.tsx:33)
    in CardSheet (at Card.tsx:573)
    in RCTView (at View.js:34)
    in Unknown (at createAnimatedComponent.js:217)
    in AnimatedComponent (at createAnimatedComponent.js:278)
    in AnimatedComponentWrapper (at Card.tsx:555)
    in PanGestureHandler (at GestureHandlerNative.tsx:13)
    in PanGestureHandler (at Card.tsx:549)
    in RCTView (at View.js:34)
    in Unknown (at createAnimatedComponent.js:217)
    in AnimatedComponent (at createAnimatedComponent.js:278)
    in AnimatedComponentWrapper (at Card.tsx:544)
    in RCTView (at View.js:34)
    in Unknown (at Card.tsx:538)
    in Card (at CardContainer.tsx:206)
    in CardContainer (at CardStack.tsx:623)
    in RCTView (at View.js:34)
    in Unknown (at Screens.tsx:84)
    in MaybeScreen (at CardStack.tsx:616)
    in RCTView (at View.js:34)
    in Unknown (at Screens.tsx:54)
    in MaybeScreenContainer (at CardStack.tsx:498)
    in CardStack (at StackView.tsx:462)
    in KeyboardManager (at StackView.tsx:458)
    in RNCSafeAreaProvider (at SafeAreaContext.tsx:76)
    in SafeAreaProvider (at SafeAreaProviderCompat.tsx:42)
    in SafeAreaProviderCompat (at StackView.tsx:455)
    in RCTView (at View.js:34)
    in Unknown (at StackView.tsx:454)
    in StackView (at createStackNavigator.tsx:87)
    in StackNavigator (at app.routes.js:22)
    in Routes (at routes/index.js:9)
    in EnsureSingleNavigator (at BaseNavigationContainer.tsx:409)
    in BaseNavigationContainer (at NavigationContainer.tsx:91)
    in ThemeProvider (at NavigationContainer.tsx:90)
    in NavigationContainer (at routes/index.js:8)
    in Routes (at App.js:21)
    in PersistGate (at App.js:19)
    in Provider (at App.js:18)
    in App (at renderApplication.js:47)
    in RCTView (at View.js:34)
    in Unknown (at AppContainer.js:107)
    in RCTView (at View.js:34)
    in Unknown (at AppContainer.js:134)
    in AppContainer (at renderApplication.js:40)

Maybe is happening because of some configuration, but I implemented:

at configuration: yarn add react-native-big-calendar
also added: yarn add @types/react @types/react-native


export default () => {
const events = [
    {
      title: 'Meeting',
      start: new Date(2020, 1, 11, 10, 0),
      end: new Date(2020, 1, 11, 10, 30),
    },
    {
      title: 'Coffee break',
      start: new Date(2020, 1, 11, 15, 45),
      end: new Date(2020, 1, 11, 16, 30),
    },
  ];

return(
 <Calendar events={events} height={300} />
)
}

Changing date prop of Calendar component not updating the Calendar UI

I've added a custom header to the calendar, where I'm allowing the change of date with prev and next buttons.
Clicking these buttons, the date is being updated and passed on to the Calendar component. But the Calendar UI remains the same. It does not change to the date. Swipping on the calendar works, but not via an external state.

Here is my code

import React, { useState } from 'react';
import { Calendar as BigCalendar } from 'react-native-big-calendar';

import CalendarHeader from './CalenderHeader';

export default function Calendar() {
  const [date, setDate] = useState<Date>(new Date());

  const handleDateChange = (updatedDate: Date) => {
    setDate(() => new Date(updatedDate));
  };

  return (
    <>
      <CalendarHeader date={date} onDateChange={handleDateChange} />
      <BigCalendar
        ampm
        mode="day"
        date={date}
        events={[
          {
            title: 'Meeting 0',
            start: new Date(date.getFullYear(), date.getMonth(), date.getDate() - 1, 3, 0),
            end: new Date(date.getFullYear(), date.getMonth(), date.getDate() - 1, 5, 0),
          },
          {
            title: 'Meeting',
            start: new Date(date.getFullYear(), date.getMonth(), date.getDate(), 10, 0),
            end: new Date(date.getFullYear(), date.getMonth(), date.getDate(), 11, 0),
          },
          {
            title: 'Coffee break',
            start: new Date(date.getFullYear(), date.getMonth(), date.getDate(), 4 + 12, 15),
            end: new Date(date.getFullYear(), date.getMonth(), date.getDate(), 4 + 12, 40),
          },
        ]}
        overlapOffset={100}
        height={680}
        renderHeader={() => null}
      />
    </>
  );
}

Here is the CalenderHeader

import React from 'react';
import { add as addDuration } from 'date-fns';

import { Text, Wrapper, Button } from '@flurn/pandora/components';
import { DateFormats, formatDate } from '@flurn/pandora/utils';

interface CalendarHeaderProps {
  date: Date;
  onDateChange: (date: Date) => void;
}

export default function CalendarHeader(props: CalendarHeaderProps): JSX.Element {
  const { date, onDateChange } = props;

  const handleDateChange = (change: number) => () => {
    onDateChange(addDuration(date, { days: change }));
  };

  return (
    <Wrapper justifyContent="space-evenly" flexDirection="row" alignItems="center" my={12}>
      <Button fullWidth={false} primary={false} label="< Prev" onPress={handleDateChange(-1)} />
      <Text bold>{formatDate({ date1: date.toString(), option: DateFormats.Day })}</Text>
      <Button fullWidth={false} primary={false} label="Next >" onPress={handleDateChange(+1)} />
    </Wrapper>
  );
}

This is happening on both Android and iOS. Tested on android device and iOS simulator.

Here is the behavior -
https://user-images.githubusercontent.com/12946926/127954631-3765fb86-8eb5-47f5-869b-8df198b2feea.mp4

In the above video, you can see that initially swiping on the screen takes me to the previous date. But when I try to click on the header buttons, I see a flicker but the current day calendar does not change.

eventRenderer should be used in `<Calendar />` component

In the current implementation of eventRenderer creates functions for each event. This is not ideal in terms of performance.

Custom render function should be like this

const eventRenderer = (event, touchableOpacityProps) => (
  <TouchableOpacity {...touchableOpacityProps}>
    <Text>{event.title}</Text>
  </TouchableOpacity>
)

<Calendar
  events={events}
  renderEvent={eventRenderer}
/>

dragging to create / move events

I have been developing with react native for a few months. How difficult is it to implement dragging to create/move events in this library? Any pointers?

Can't get the react-native example to work on android

I want to contribut to the module but as the title suggests I can't get the react-native example to work on android. I cloned the project and then ran:

$yarn install
$yarn build
$yarn sync-ios
$cd rndemo
$yarn react-native run-android

The app keeps crashing with the error:

Error: Unable to resulve module './Calendar.tsx' from 'build\index.js'

The index.js file inside the build folder is as follows:

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var Calendar_tsx = require('./Calendar.tsx');
var interfaces_ts = require('./interfaces.ts');



Object.keys(interfaces_ts).forEach(function (k) {
	if (k !== 'default') Object.defineProperty(exports, k, {
		enumerable: true,
		get: function () {
			return interfaces_ts[k];
		}
	});
});
Object.defineProperty(exports, 'Calendar', {
	enumerable: true,
	get: function () {
		return Calendar_tsx.Calendar;
	}
});
//# sourceMappingURL=index.js.map

I looked at the buld folder and it does not include any .tsx files so I think there might be a problem with the build process.

Adding custom styles to stacked events

Ran into an issue when creating custom colors for events. I have two events with same colour on top of each other. I'm trying to separate them visually using box shadow but for some reason box shadow styling doesn't seem to be applied to the component on top. Is there some override there?

If there was some property passed to eventCellStyle which would indicate if a component is on top of another I could use border to separate those but I don't want to add borders to all of my events to solve this issue. Any ideas?

Calendar hours range

Hello,

thank you for the great library it is really awsome good work,

I am actually trying to change the hours range from [00:00-23:00] to [08:00-19:00], i have tried to change the hours variable in index.js, but the events are no longer aligned with their proper HourGuideColumn, can you help please ?

Thank you in advance

Scrolling Issue

Hi,
The calendar is not scrolling inside a ScrollView in android. Working perfectly on ios.

Dynamic colors of events

Is it possible to set own backgroundColors for the events passed from events-array? How to use the prop eventCellStyle to change the color dynamic?

If I have data like:

title: event.title,
start: event.start,
end: event.end,
color: event.colorCode

Additional Styling Enhancements

Can we please consider adding the following styling TODOs:

  • Ability to customize the hour sidebar (colors, fonts etc)
  • Ability to customize the font in an event cell
  • Ability to customize grid line style

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.