Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-native-calendar-line

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-native-calendar-line

Calendar Component for React Native

  • 1.0.0
  • unpublished
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

react-native-calendar-line

Calendar Component for React Native

platforms npm package version project license

Table of Contents

  • Install
  • Usage
  • Props
  • Animations
  • Localization
  • Device Specific Notes
  • Local Development
  • Contributing
  • License
  • Install

    $ npm install react-native-calendar-line
    # OR
    $ yarn add react-native-calendar-line
    

    Usage

    CalendarLine

    The scrollable prop features a bi-directional infinite scroller. It recycles days using RecyclerListView, shifting the dates as the ends are reached. The Chrome debugger can cause issues with this updating due to a RN setTimeout bug. To prevent date shifts at the ends of the scroller, set the minDate and maxDate range to a year or less.

    The refactor to support scrollable introduced internal changes to the CalendarDay component. Users of the dayComponent prop may need to adjust their custom day component to accommodate the props passed to it.

    import { View, StyleSheet } from 'react-native';
    import CalendarLine from 'react-native-calendar-line';
    
    const Example = () => (
      <View style={styles.container}>
        <CalendarLine
          scrollable
          style={{height:200, paddingTop: 20, paddingBottom: 10}}
          calendarColor={'#3343CE'}
          calendarHeaderStyle={{color: 'white'}}
          dateNumberStyle={{color: 'white'}}
          dateNameStyle={{color: 'white'}}
          iconContainer={{flex: 0.1}}
        />
      </View>
    );
    
    const styles = StyleSheet.create({
      container: { flex: 1 }
    });
    

    Simple "out of the box" Example

    You can use this component without any styling or customization. Just import it in your project and render it:

    import { View, StyleSheet } from 'react-native';
    import CalendarLine from 'react-native-calendar-line';
    
    const Example = () => (
      <View style={styles.container}>
        <CalendarLine
          style={{height:150, paddingTop: 20, paddingBottom: 10}}
        />
      </View>
    );
    
    const styles = StyleSheet.create({
      container: { flex: 1 }
    });
    

    Styling and animations Example

    Even though this component works withouth any customization, it is possible to customize almost everything, so you can make it as beautiful as you want:

    import React, {Component} from 'react';
    import {
        AppRegistry,
        View
    } from 'react-native';
    import moment from 'moment';
    
    import CalendarLine from 'react-native-calendar-line';
    
    class Example extends Component {
        let datesWhitelist = [{
          start: moment(),
          end: moment().add(3, 'days')  // total 4 days enabled
        }];
        let datesBlacklist = [ moment().add(1, 'days') ]; // 1 day disabled
    
        render() {
            return (
                <View>
                    <CalendarLine
                        calendarAnimation={{type: 'sequence', duration: 30}}
                        daySelectionAnimation={{type: 'border', duration: 200, borderWidth: 1, borderHighlightColor: 'white'}}
                        style={{height: 100, paddingTop: 20, paddingBottom: 10}}
                        calendarHeaderStyle={{color: 'white'}}
                        calendarColor={'#7743CE'}
                        dateNumberStyle={{color: 'white'}}
                        dateNameStyle={{color: 'white'}}
                        highlightDateNumberStyle={{color: 'yellow'}}
                        highlightDateNameStyle={{color: 'yellow'}}
                        disabledDateNameStyle={{color: 'grey'}}
                        disabledDateNumberStyle={{color: 'grey'}}
                        datesWhitelist={datesWhitelist}
                        datesBlacklist={datesBlacklist}
                        iconLeft={require('./img/left-arrow.png')}
                        iconRight={require('./img/right-arrow.png')}
                        iconContainer={{flex: 0.1}}
                    />
                </View>
            );
        }
    }
    
    AppRegistry.registerComponent('Example', () => Example);
    

    Props

    Initial data and onDateSelected handler

    PropDescriptionTypeDefault
    numDaysInWeekNumber of days shown in week. Applicable only when scrollable is false.Number7
    scrollableDates are scrollable if true.BoolFalse
    scrollerPagingDates are scrollable as a page (7 days) if true (Only works with scrollable set to true).BoolFalse
    startingDateDate to be used for centering the calendar/showing the week based on that date. It is internally wrapped by moment so it accepts both Date and moment Date.Any
    selectedDateDate to be used as pre selected Date. It is internally wrapped by moment so it accepts both Date and moment Date.Any
    onDateSelectedFunction to be used as a callback when a date is selected. Receives param date Moment date.Function
    onWeekChangedFunction to be used as a callback when a week is changed. Receives params (start, end) Moment dates.Function
    onWeekScrollStartFunction to be used as a callback in scrollable mode when dates page starts gliding. Receives params (start, end) Moment dates.Function
    onWeekScrollEndFunction to be used as a callback in scrollable mode when dates page stops gliding. Receives params (start, end) Moment dates.Function
    onHeaderSelectedFunction to be used as a callback when the header is selected. Receives param object {weekStartDate, weekEndDate} Moment dates.Function
    headerTextText to use in the header. Use with onWeekChanged to receive the visible start & end dates.String
    updateWeekUpdate the week view if other props change. If false, the week view won't change when other props change, but will still respond to left/right selectors.BoolTrue
    useIsoWeekdaystart week on ISO day of week (default true). If false, starts week on startingDate parameter.BoolTrue
    minDateminimum date that the calendar may navigate to. A week is allowed if minDate falls within the current week.Any
    maxDatemaximum date that the calendar may navigate to. A week is allowed if maxDate falls within the current week.Any
    datesWhitelistArray of dates that are enabled, or a function callback which receives a date param and returns true if enabled. Array supports ranges specified with an object entry in the array. Check example BelowArray or Func
    datesBlacklistArray of dates that are disabled, or a function callback. Same format as datesWhitelist. This overrides dates in datesWhitelist.Array or Func
    markedDatesDates that are marked with dots or lines. Format as markedDatesFormat.Array or Func[]
    scrollToOnSetSelectedDateControls whether to reposition the scroller to the date passed to setSelectedDate.BoolTrue
    datesWhitelist Array Example
      datesWhitelist = [
        // single date (today)
        moment(),
    
        // date range
        {
          start: (Date or moment Date),
          end: (Date or moment Date)
        }
      ];
    
      return (
        <CalendarLine
          datesWhitelist={datesWhitelist}
        />
      );
    
    datesBlacklist Callback Example
      const datesBlacklistFunc = date => {
        return date.isoWeekday() === 6; // disable Saturdays
      }
    
      return (
        <CalendarLine
          datesBlacklist={datesBlacklistFunc}
        />
      );
    
    markedDates Example
    marked dates example

    markedDates may be an array of dates with dots/lines, or a callback that returns the same shaped object for a date passed to it.

      // Marked dates array format
      markedDatesArray = [
        {
          date: '(string, Date or Moment object)',
          dots: [
            {
              color: <string>,
              selectedColor: <string> (optional),
            },
          ],
        },
        {
          date: '(string, Date or Moment object)',
          lines: [
            {
              color: <string>,
              selectedColor: <string> (optional),
            },
          ],
        },
      ];
    
    
      // Marked dates callback
      markedDatesFunc = date => {
        // Dot
        if (date.isoWeekday() === 4) { // Thursdays
          return {
            dots:[{
              color: <string>,
              selectedColor: <string> (optional),
            }]
          };
        }
        // Line
        if (date.isoWeekday() === 6) { // Saturdays
          return {
            lines:[{
              color: <string>,
              selectedColor: <string> (optional),
            }]
          };
        }
        return {};
      }
    
    

    Hiding Components

    PropDescriptionTypeDefault
    showMonthShow or hide the month label.BoolTrue
    showDateShow or hide all the dates.BoolTrue
    showDayNameShow or hide the day name labelBoolTrue
    showDayNumberShow or hide the day number labelBoolTrue

    Styling

    PropDescriptionTypeDefault
    styleStyle for the top level CalendarLine component.Any
    innerStyleStyle for the responsively sized inner view. This is necessary to account for padding/margin from the top level view. The inner view has style flex:1 by default. If this component is nested within another dynamically sized container, remove the flex style by passing in [].Any
    calendarHeaderStyleStyle for the header text of the calendarAny
    calendarHeaderContainerStyleStyle for the header text wrapper of the calendarAny
    calendarHeaderPositionPosition of the header text (above or below)above, belowabove
    calendarHeaderFormatFormat for the header text of the calendar. For options, refer to Moment documentationString
    dateNameStyleStyle for the name of the day on work days in dates stripAny
    dateNumberStyleStyle for the number of the day on work days in dates strip.Any
    dayContainerStyleStyle for all day containers. RNCS scales the width & height responsively, so take that into account if overriding them.Any
    weekendDateNameStyleStyle for the name of the day on weekend days in dates strip.Any
    weekendDateNumberStyleStyle for the number of the day on weekend days in dates strip.Any
    styleWeekendWhether to style weekend dates separately.BoolTrue
    highlightDateNameStyleStyle for the selected name of the day in dates strip.Any
    highlightDateNumberStyleStyle for the selected number of the day in dates strip.Any
    highlightDateNumberContainerStyleStyle for the selected date number container. Similar to highlightDateNumberStyle, but this fixes the issue that some styles may have on iOS when using highlightDateNumberStyle.Any
    highlightDateContainerStyleStyle for the selected date container.Object
    disabledDateNameStyleStyle for disabled name of the day in dates strip (controlled by datesWhitelist & datesBlacklist).Any
    disabledDateNumberStyleStyle for disabled number of the day in dates strip (controlled by datesWhitelist & datesBlacklist).Any
    markedDatesStyleStyle for the marked dates marker.Object
    disabledDateOpacityOpacity of disabled dates strip.Number0.3
    customDatesStylesCustom per-date styling, overriding the styles above. Check Table Below .Array or Func[]
    shouldAllowFontScalingOverride the underlying Text element scaling to respect font settingsBoolTrue
    upperCaseDaysFormat text of the days to upper case or title caseBoolTrue
    customDatesStyles
    Custom date styling example

    This prop may be passed an array of style objects or a callback which receives a date param and returns a style object for it. The format for the style object follows:

    KeyDescriptionTypeoptional
    startDateanything parseable by Moment.AnyFalse (unused w/ callback)
    endDatespecify a range. If no endDate is supplied, startDate is treated as a single date.AnyTrue (unused w/ callback)
    dateNameStyleText style for the name of the day.AnyTrue
    dateNumberStyleText style for the number of the day.AnyTrue
    highlightDateNameStyleText style for the selected name of the day. This overrides the global prop.AnyTrue
    highlightDateNumberStyleText style for the selected number of the day. This overrides the global prop.AnyTrue
    dateContainerStyleStyle for the date Container.AnyTrue
    Array Usage Example:
      let customDatesStyles = [];
      let startDate = moment();
      for (let i=0; i<6; i++) {
        customDatesStyles.push({
            startDate: startDate.clone().add(i, 'days'), // Single date since no endDate provided
            dateNameStyle: styles.dateNameStyle,
            dateNumberStyle: styles.dateNumberStyle,
            // Random color...
            dateContainerStyle: { backgroundColor: `#${(`#00000${(Math.random() * (1 << 24) | 0).toString(16)}`).slice(-6)}` },
          });
      }
    
      render() {
        return (
          <CalendarLine
            customDatesStyles={customDatesStyles}
            ...
          />
        );
      }
    
    Callback Usage Example:
      const customDatesStylesFunc = date => {
        if (date.isoWeekday() === 5) { // Fridays
          return {
            dateNameStyle: {color: 'blue'},
            dateNumberStyle: {color: 'purple'},
            dateContainerStyle:  {color: 'yellow'},
          }
        }
      }
    
      render() {
        return (
          <CalendarLine
            customDatesStyles={customDatesStylesFunc}
            ...
          />
        );
      }
    
    Responsive Sizing
    PropDescriptionTypeDefault
    maxDayComponentSizeMaximum size that CalendarDay will responsively size up to.Number80
    minDayComponentSizeMinimum size that CalendarDay will responsively size down to.Number10
    responsiveSizingOffsetAdjust the responsive sizing. May be positive (increase size) or negative (decrease size). This value is added to the calculated day component widthNumber0
    dayComponentHeightFixed height for the CalendarDay component or custom dayComponent.Number
    Icon Sizing
    PropDescriptionTypeDefault
    iconLeftIcon to be used for the left icon. It accepts require statement with url to the image (require('./img/icon.png')), or object with remote uri {uri: 'http://example.com/image.png'}Any
    iconRightIcon to be used for the right icon. It accepts require statement with url to the image (require('./img/icon.png')), or object with remote uri {uri: 'http://example.com/image.png'}Any
    iconStyleStyle that is applied to both left and right icons. It is applied before iconLeftStyle or iconRightStyle.Any
    iconLeftStyleStyle for left icon. It will override all of the other styles applied to icons.Any
    iconRightStyleStyle for right icon. It will override all of the other styles applied to icons.Any
    iconContainerStyle for the container of icons. (Example usage is to add flex property to it so in the portrait mode, it will shrink the dates strip)Any
    leftSelectorComponent for the left selector control. May be an instance of any React component. This overrides the icon* props above. Passing in an empty array [] hides this control.Any
    rightSelectorComponent for the right selector control. May be an instance of any React component. This overrides the icon* props above. Passing in an empty array [] hides this control.Any
    Custom Day component
    PropDescriptionTypeDefault
    dayComponentUser-defined component for the Days. All day-related props are passed to the custom component.Any

    Methods

    Methods may be accessed through the instantiated component's ref.

    PropDescription
    getSelectedDate()Returns the currently selected date. If no date is selected, returns undefined.
    setSelectedDate(date)Sets the selected date. date may be a Moment object, ISO8601 date string, or any format that Moment is able to parse. It is the responsibility of the caller to select a date that makes sense (e.g. within the current week view). Passing in a value of 0 effectively clears the selected date. scrollToOnSetSelectedDate controls whether the scroller repositions to the selected date.
    getNextWeek()Advance to the next week.
    getPreviousWeek()Rewind to the previous week.
    updateWeekView(date)Show the week starting on date.

    Animations

    Week Strip Animation

    Sequence example (dates shown one by one)Parallel example (dates shown all at once)
    alt textalt text
    Week Strip Animation Options

    The calendarAnimation prop accepts an object in the following format:

    PropsDescriptionTypes
    TypePick which type of animation you would like to showsequence or parallel
    durationduration of animation in millisecondsNumber (ms)
    useNativeDriverUse Animated's native driver (default true)Bool

    Day Selection Animation

    Border exampleBackground example
    alt textalt text
    Day Selection Animation Options

    The daySelectionAnimation prop accepts an object in the following format:

    PropsDescriptionType
    TypePick which type of animation you would like to showborder or background
    durationduration of animation in millisecondsNumber (ms)
    borderWidthSelected day's border width. Required if the type is set to border.Number
    borderHighlightColorSelected day's border color. Required if the type is set to border.String
    highlightColorHighlighted color of selected date. Required if the type is set to background.String
    animTypeoptional config options passed to LayoutAnimationany
    animUpdateTypeoptional config options passed to LayoutAnimationany
    animPropertyoptional config options passed to LayoutAnimationany
    animSpringDampingoptional config options passed to LayoutAnimationany

    Localization

    PropsDescriptionType
    localeLocale for datesObject

    This prop is used for adding localization to react-native-calendar-line component. The localization rules are the same as moments and can be found in moments documentation

    locale PropsDescriptionType
    nameThe name of the locale (ex. 'fr')String
    configThe config object holding all of the localization strings..Object
    Build Release info

    To properly make a release build, import the appropriate "Locale" module using the following steps. Not importing the locale module will crash the release build (though the dev build will work).

    1- import momentJs module:

    $ yarn add moment

    or

    $ npm install moment

    2- Go to your index.js and import the specific "Locale" after the main moment import. Ex:

    import 'moment';
    import 'moment/locale/fr';  // language must match config
    import moment from 'moment-timezone';  // only if timezone is needed
    

    The locale import must match the language specified in the locale config (example below).

    Example of one locale object is:
    const locale = {
      name: 'fr',
      config: {
        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('_'),
        weekdaysMin: 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'),
        longDateFormat: {
          LT: 'HH:mm',
          LTS: 'HH:mm:ss',
          L: 'DD/MM/YYYY',
          LL: 'D MMMM YYYY',
          LLL: 'D MMMM YYYY LT',
          LLLL: 'dddd D MMMM YYYY LT'
        },
        calendar: {
          sameDay: "[Aujourd'hui à] LT",
          nextDay: '[Demain à] LT',
          nextWeek: 'dddd [à] LT',
          lastDay: '[Hier à] LT',
          lastWeek: 'dddd [dernier à] LT',
          sameElse: 'L'
        },
        relativeTime: {
          future: 'dans %s',
          past: 'il y a %s',
          s: 'quelques secondes',
          m: 'une minute',
          mm: '%d minutes',
          h: 'une heure',
          hh: '%d heures',
          d: 'un jour',
          dd: '%d jours',
          M: 'un mois',
          MM: '%d mois',
          y: 'une année',
          yy: '%d années'
        },
        ordinalParse: /\d{1,2}(er|ème)/,
        ordinal: function(number) {
          return number + (number === 1 ? 'er' : 'ème');
        },
        meridiemParse: /PD|MD/,
        isPM: function(input) {
          return input.charAt(0) === 'M';
        },
        // in case the meridiem units are not separated around 12, then implement
        // this function (look at locale/id.js for an example)
        // meridiemHour : function (hour, meridiem) {
        //     return /* 0-23 hour, given meridiem token and hour 1-12 */
        // },
        meridiem: function(hours, minutes, isLower) {
          return hours < 12 ? 'PD' : 'MD';
        },
        week: {
          dow: 1, // Monday is the first day of the week.
          doy: 4 // The week that contains Jan 4th is the first week of the year.
        }
      }
    };
    

    Device Specific Notes

    • OnePlus devices use OnePlus Slate font by default which causes text being cut off in the date number in react-native-calendar-line. To overcome this change the default font of the device or use a specific font throughout your app.

    Keywords

    FAQs

    Package last updated on 17 Jul 2022

    Did you know?

    Socket

    Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

    Install

    Related posts

    SocketSocket SOC 2 Logo

    Product

    • Package Alerts
    • Integrations
    • Docs
    • Pricing
    • FAQ
    • Roadmap
    • Changelog

    Packages

    npm

    Stay in touch

    Get open source security insights delivered straight into your inbox.


    • Terms
    • Privacy
    • Security

    Made with ⚡️ by Socket Inc