rnw
react-native-week-view
npm i react-native-week-view
rnw

react-native-week-view

Week View Component for react-native

by Hoang Nguyen

0.28.0 (see all)License:MITTypeScript:Built-In
npm i react-native-week-view
Readme

tests linter codeql

react-native-week-view

The week view component for react-native.

  • Supported in Android and iOS
  • Many user interactions supported: drag and drop events, edit events, swipe through pages, event press, grid press, etc
  • Customizable styles
  • Multiple locale support

weekView

Table of Contents

Installation

npm install --save react-native-week-view

or

yarn add react-native-week-view

Requirements: install peer dependencies react-native-gesture-handler v2 and react-native-reanimated v2, which we use to provide smoother interactions and animations (e.g. drag and drop). Required by react-native-week-view since versions 0.17.0 and higher.

Compatibility:

react-native-week-viewreact-native
>= 0.7.0>= 0.59
>= 0.17.0>= 0.60.0

Basic usage

import WeekView from 'react-native-week-view';

const myEvents = [
  {
    id: 1,
    description: 'Event',
    startDate: new Date(2021, 3, 15, 12, 0),
    endDate: new Date(2021, 3, 15, 12, 30),
    color: 'blue',
    // ... more properties if needed,
  },
  // More events...
];

const MyComponent = () => (
  <WeekView
    events={myEvents}
    selectedDate={new Date(2021, 3, 15)}
    numberOfDays={7}
  />
);

Example use cases

See dedicated docs with common usages and example code.

Changelog

API is still unstable, minor updates before v1.0.0 can include breaking changes, adhering to Semantic Versioning. See CHANGELOG.md for details.

Full API

Props

Prop nameTypeDefaultDescription
eventsArrayrequiredEvents to display, in Event Item format (see below).
selectedDateDaterequiredDate to show the week-view in the first render. Note: changing this prop after the first render will not have any effect in the week-view; to actually move the week-view, use the goToDate() method, see below.
numberOfDaysNumber, one of 1, 3, 5, 7requiredNumber of days to show in the week-view.
Gesture
interactions
onEventPressFunction: (event) => {}nullCallback when an event item is pressed, receives the event-item pressed: (event) => {}.
onEventLongPressFunction: (event) => {}nullCallback when an event item is long pressed, same signature as onEventPress.
onSwipeNextFunction: (date) => {}nullCallback when week-view is swiped to next week/days, receives new date shown.
onSwipePrevFunction: (date) => {}nullCallback when week-view is swiped to previous week/days, same signature as onSwipeNext.
onGridClickFunction: (pressEvent, startHour, date) => {}nullCallback when the grid view is pressed. Arguments: pressEvent: object passed by the react-native-gesture-handler touch events (not an event item); startHour: Number, hour pressed; date Date, date object indicating day and time pressed with precision up to seconds. Note: startHour is redundant (can be extracted from date), but is kept for backward-compatibility.
onGridLongPressFunction: (pressEvent, startHour, date) => {}nullCallback when the grid view is long-pressed. Same signature as onGridClick
onDayPressFunction: (date, formattedDate) => {}nullCallback when a day from the header is pressed.
onMonthPressFunction: (date, formattedDate) => {}nullCallback when the month at the top left (title) is pressed.
onTimeScrolledFunction: (dateWithTime) => {}nullCallback when the agenda is scrolled vertically.
onDragEventFunction: (event, newStartDate, newEndDate) => update DBnullCallback when an event item is dragged to another position. Arguments: event: event-item moved, and the newStartDate and newEndDate are Date objects with day and hour of the new position (precision up to minutes). With this callback you must trigger an update on the events prop (i.e. update your DB), with the updated information from the event.
dragEventConfig{afterLongPressDuration: milliseconds}{afterLongPressDuration: 0}If provided, events are only draggable after being long pressed for some time. Requires rn-gesture-handler v2.6.0 or higher. Disables the onLongPress callback.
onEditEventFunction: (event, newStartDate, newEndDate) => update DBnullCallback when an event item is edited by dragging its borders.
editingEventNumber | String | nullnullEvent id indicating the event currently being edited.
editEventConfig{bottom: bool, top: bool, left: bool, right: bool}null_{bottom: true}
Week-view
customizations
startHourNumber, in hours8 (8 am)Vertical position of the week-view in the first render (vertically in the agenda).
pageStartAt{left: number, weekday: number}{left:0}Indicates what date to show in the top-left corner. If left = value provided, the selectedDate will appear at value days from the left. If weekday = value (e.g. tuesday = 2) is provided, the latest tuesday will appear in the left.
allowScrollByDayBooleanfalseWhen true, the component can scroll horizontally one day at the time. When false, the horizontal scroll can only be done one page at the time (i.e. numberOfDays at the time).
showTitleBooleantrueShow or hide the selected month and year in the top-left corner (a.k.a the title).
hoursInDisplayNumber, in hours6Amount of hours to display vertically in the agenda. Increasing this number will make the events look smaller.
beginAgendaAtNumber, in minutes0 (0h)Time of day to start the agenda at the top (grid above is left out). For example, for 8 am set beginAgendaAt={8*60}.
endAgendaAtNumber, in minutes24 * 60 (24h)Time of day to end the agenda at the bottom (grid below is left out). For example, for 10pm set engAgendaAt={22*60}.
timeStepNumber, in minutes60Number of minutes to use as step in the time labels at the left. Increasing this number will increase the vertical space between grid lines.
formatDateHeaderString"MMM D" (e.g. "Apr 3")Formatter for dates in the header. See all formatters in momentjs.
formatTimeLabelString"H:mm" (24 hours)Formatter for the time labels at the left. Other examples, AM/PM: "h:mm A" or "h:mm a" for lowercase. See all formatters in momentjs.
timesColumnWidthNumber0.18 (18% of screen-width)Customize the width of the times column at the left. If the value is in range 0..1 indicates a percentage of the screen width (e.g. 0.18 --> 18%). Otherwise is the amount of pixels (e.g. 40 pixels).
EventComponentReactComponentTextCustom component rendered inside an event. By default, is a Text with the event.description. See sub-section below for details on the component.
TodayHeaderComponentReactComponentnullCustom component to highlight today in the header (by default, today looks the same than every day). See details in sub-section below
DayHeaderComponentReactComponentnullCustom component to show each day in the header. If provided, overrides TodayHeaderComponent. See details in sub-section below
showNowLineBooleanfalseIf true, displays a line indicating the time right now.
nowLineColorStringred (#E53935)Color used for the now-line.
fixedHorizontallyBooleanfalseIf true, the component can be used to display a single fixed week. See example in sub-section below.
isRefreshingBooleanfalseWhen true, the week-view will show an <ActivityIndicator /> in the middle of the grid.
RefreshComponentReactComponentActivityIndicatorCustom component used when isRefreshing is true. See example below.
localeString"en"Locale for the dates (e.g. header). There's an addLocale() function to add customized locale, see below.
rightToLeftBooleanfalseIf true, render older days to the right and more recent days to the left.
Style
props
headerStyleObject-Custom styles for header container. Example: { backgroundColor: '#4286f4', color: '#fff', borderColor: '#fff' }
headerTextStyleObject-Custom styles for text inside header. Applied to day names and month name (i.e. title)
hourTextStyleObject-Custom styles for text displaying hours at the left.
eventContainerStyleObject-Custom styles for each event item container. Note: the background color and (absolute) positioning are already set.
Grid lines
props
gridRowStyleObjectwidth: 1, color: grey (#E9EDF0)Prop to customize width and color of horizontal lines, provide: { borderTopWidth: <width>, borderColor: <color> }
gridColumnStyleObjectsame as aboveProp to customize width and color of vertical lines, provide: { borderLeftWidth: <width>, borderColor: <color> }
Horizontal list optimizations
(see known issues)
windowSizeNumber5Number of pages to render at the same time. One page is composed by numberOfDays days. See in optimizing FlatList docs
initialNumToRenderNumber5Initial number of pages to render. See in optimizing FlatList docs
maxToRenderPerBatchNumber2See in optimizing FlatList docs.
updateCellsBatchingPeriodNumber50See in optimizing FlatList docs
Other props
(patch RN bugs)
prependMostRecentBooleanfalseIf true, the horizontal prepending is done in the most recent dates when scrolling. See known issues

Event Item

{
  // Basic fields:
  id: 1,
  description: 'Event',
  startDate: new Date(2021, 3, 15, 12, 0),
  endDate: new Date(2021, 3, 15, 12, 30),
  color: 'blue',

  // Special fields for extra features, details below. e.g.:
  style: { borderColor: 'red' },

  // ... your custom fields if needed,
}

Special fields

There are some fields in the EventItem that provide extra customizations for each event.

Extra EventItem fieldsTypeDefaultDescription
styleObjectnullProvide extra styling for the container.
disableDragboolfalseDisables drag-and-drop interaction.
disablePressboolfalseDisables onPress interaction.
disableLongPressboolfalseDisables onLongPress interaction.
Block-like events
eventKind'block' | 'standard''standard'Defines the type of event
Event overlaps
resolveOverlap'lane' | 'stack' | 'ignore''lane'Defines the method to resolve overlaps for that event.
stackKeyStringnullLimit the events it can be stacked with. If is null, it can be stacked with any other event. Only useful if resolveMethod = 'stack'

Methods

  • goToDate(date, {animated = true, left: number = null}): navigate to a custom date. If left = value is provided, the target date will appear at value days from the left (e.g. use left = 0 to show date at the most left). Note: left will require using allowScrollByDay={true} in most cases.
  • goToNextDay({animated = true}): navigate to the next day (to the future).
  • goToPrevDay({animated = true}): navigate to the previous day (to the past).
  • goToNextPage({animated = true}): navigate to the next page (to the future).
  • goToPrevPage({animated = true}): navigate to the previous page (to the past).
  • scrollToTime(minutes, options = { animated = false }): scroll vertically to a time in the day, provided in minutes. For example, scroll to 13:00 hrs: ref.scrollToTime(13 * 60).

To save a reference to the component:

<WeekView
  // class components:
  ref={(ref) => { this.weekViewRef = ref; }}
  // functional components:
  ref={weekViewRef} // with `const weekViewRef = React.useRef()`
/>

Custom components

Further customize the week-view by providing your own components.

Custom Event item component

The custom component will be rendered inside a TouchableOpacity, which has the background color set to event.color, and is placed with absolute position in the grid. The component receives two props:

  • event (Event) - Event item as described before.
  • position: (Object) - object containing top, left, height and width values in pixels.

For example, to display an icon inside each event, such as a react-native-elements Icon:

const MyEventComponent = ({ event, position }) => (
  <Icon
    name={event.iconName}
    type={event.iconType}
    color={event.color}
    size={position.height}
  />
);

<WeekView
  // ... other props
  EventComponent={MyEventComponent}
/>

Custom Day header component

(Note: first you should check if the props headerStyle, headerTextStyle and/or formatDateHeader are enough for your use case).

Use these props to fully customize the days in the header.

  • TodayHeaderComponent: to highlight today in the header, by rendering it differently from the other days.
  • DayHeaderComponent: to render every day in the header. Overrides the prop TodayHeaderComponent.

Both components would receive these props:

  • date (moment Date) - moment date object containing today's date.
  • formattedDate (String) - day formatted according to formatDateHeader, e.g. "Mon 3".
  • textStyle (Object) - text style used for every day.
  • isToday (Bool) - indicate if the date is today or not.

Examples:

// Highlight today with a bold font
const MyTodayComponent = ({ formattedDate, textStyle }) => (
  <Text style={[textStyle, { fontWeight: 'bold' }]}>{formattedDate}</Text>
);

// Add text to the header
const MyDayComponent = ({ formattedDate, textStyle, isToday }) => (
  <Text style={textStyle}>Some text - {formattedDate}</Text>
);

<WeekView
  TodayHeaderComponent={MyTodayComponent}
  // or:
  DayHeaderComponent={MyDayComponent}
/>

Locales customization

There's a addLocale function to add customized locale for the component. The component depends on momentjs, you can refer to https://momentjs.com/docs/#/customization/ for more information.

Example:

export WeekView, { addLocale } from 'react-native-week-view';
// add customized localed before using locale prop.
addLocale('fr', {
  months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
  monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
  weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
  weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
});

Custom RefreshComponent

  • RefreshComponent is a ReactComponent that receives a style prop that must be used (since it sets the component position).
  • Note: the ActivityIndicator default color in some devices may be white.

Example:

const MyRefreshComponent = ({ style }) => (
  <Text style={style}>loading...</Text>
);

<WeekView
  // ... other props
  RefreshComponent={MyRefreshComponent}
/>

Known issues

We try to make all user interactions and animations as smooth as possible, but we have seen issues in some cases.

Glitch when swiping to new pages

  • When navigating to a new distant date (e.g. using weekViewRef.goToDate(someDistantDate)) there may be a delay on the animation
  • Flicker issue when swiping to one side
    • See https://github.com/hoangnm/react-native-week-view/issues/39 for details
    • As a workaround, you can prioritize navigations to the past XOR to the future:
      • if prependMostRecent={false} (default) the swiping to the future will be smooth, but the swiping to the past pages may have glitches
      • if prependMostRecent={true}, the swiping to the past will be smooth, but swiping to the future may have glitches
  • There may be blank spaces when swiping right or left

Contributors

Made with contrib.rocks.