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

react-native-calendar-picker

Package Overview
Dependencies
Maintainers
2
Versions
72
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-native-calendar-picker

Calendar Picker Component for React Native

  • 6.1.3
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
23K
decreased by-3.4%
Maintainers
2
Weekly downloads
 
Created
Source

react-native-calendar-picker

npm version npm Build Status

This is a Calendar Picker Component for React Native

alt tag

To use the calendar you just need to:

npm install --save react-native-calendar-picker

Note: react-native-calendar-picker v5 is a complete re-write of the calendar. This calendar is now written using ES6 syntax. I kept most of the same functionalities and added support for date ranges.

If you need the old code I saved it on a branch v4

Prerequisites

CalendarPicker requires Moment JS >=2.0. Date props may be anything parseable by Moment: Javascript Date, Moment date, or ISO8601 datetime string.

npm install --save moment

Example

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View
} from 'react-native';
import CalendarPicker from 'react-native-calendar-picker';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedStartDate: null,
    };
    this.onDateChange = this.onDateChange.bind(this);
  }

  onDateChange(date) {
    this.setState({
      selectedStartDate: date,
    });
  }
  render() {
    const { selectedStartDate } = this.state;
    const startDate = selectedStartDate ? selectedStartDate.toString() : '';
    return (
      <View style={styles.container}>
        <CalendarPicker
          onDateChange={this.onDateChange}
        />

        <View>
          <Text>SELECTED DATE:{ startDate }</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
    marginTop: 100,
  },
});

CalendarPicker Props

PropTypeDescription
weekdaysArrayOptional. List of week days. Eg. ['Mon', 'Tue', ...] Must be 7 days
monthsArrayOptional. List of months names. Eg. ['Jan', 'Feb', ...] Must be 12 months
startFromMondayBooleanOptional. Default first day of week will be Sunday. You can set start of week from Monday by setting this to true. Default is false
showDayStragglersBooleanOptional. Populate previous & next month days in empty slots. Default is false
allowRangeSelectionBooleanOptional. Allow to select date ranges. Default is false
allowBackwardRangeSelectBooleanOptional. Allow selecting range in reverse. Default is false
previousTitleStringOptional. Title of button for previous month. Default is Previous
nextTitleStringOptional. Title of button for next month. Default is Next
previousTitleStyleTextStyleOptional. Text styling for Previous text.
nextTitleStyleTextStyleOptional. Text styling for Next text.
previousComponentObjectOptional. Component to use in Previous button. Overrides previousTitle & previousTitleStyle.
nextComponentObjectOptional. Component to use in Next button. Overrides nextTitle & nextTitleStyle.
selectedDayColorStringOptional. Color for selected day
selectedDayStyleViewStyleOptional. Style for selected day. May override selectedDayColor.
selectedDayTextColorStringOptional. Text color for selected day
selectedRangeStartStyleViewStyleOptional. Style for range selected start day.
selectedRangeEndStyleViewStyleOptional. Style for range selected end day.
selectedRangeStyleViewStyleOptional. Style for all days in range selection.
disabledDatesArray or FunctionOptional. Specifies dates that cannot be selected. Array of Dates, or a function that returns true for a given Moment date (apologies for the inverted logic).
disabledDatesTextStyleTextStyleOptional. Text styling for disabled dates.
selectedStartDateDateOptional. Specifies a selected Start Date.
selectedEndDateDateOptional. Specifies a selected End Date.
minRangeDurationNumber or ArrayOptional. Specifies a minimum range duration when using allowRangeSelection. Can either pass a number to be used for all dates or an Array of objects if the minimum range duration depends on the date {date: Moment-parsable date, minDuration: Number}
maxRangeDurationNumber or ArrayOptional. Specifies a maximum range duration when using allowRangeSelection. Can either pass a number to be used for all dates or an Array of objects if the maximum range duration depends on the date {date: Moment-parsable date, maxDuration: Number}
todayBackgroundColorStringOptional. Background color for today. Default is #cccccc
todayTextStyleTextStyleOptional. Text styling for today.
textStyleTextStyleOptional. Style overall text. Change fontFamily, color, etc.
customDatesStylesArrayOptional. Style individual date(s). Array of objects {date: Moment-parseable date, containerStyle: ViewStyle, style: ViewStyle, textStyle: TextStyle}
customDatesStylesPriorityStringOptional. Precedence of customDates or dayOfWeek styles. Default dayOfWeek
scaleFactorNumberOptional. Default (375) scales to window width
minDateDateOptional. Specifies minimum date to be selected
maxDateDateOptional. Specifies maximum date to be selected
initialDateDateOptional. Date that calendar opens to. Defaults to today.
widthNumberOptional. Width of CalendarPicker's container. Defaults to Dimensions width.
heightNumberOptional. Height of CalendarPicker's container. Defaults to Dimensions height.
swipeConfigObjectOptional. Config passed to Swiper.
enableSwipeBooleanOptional. Whether to enable swiping. Default is true
enableDateChangeBooleanOptional. Whether to enable pressing on day. Default is true
restrictMonthNavigationBooleanOptional. Whether to disable Previous month button if it is before minDate or Next month button if it is after MaxDate. Default is false
onDateChangeFunctionOptional. Callback when a date is selected. Returns Moment date as first param; START_DATE or END_DATE as second param.
onMonthChangeFunctionOptional. Callback when Previous / Next month is pressed. Returns Moment date as first parameter.
onSwipeFunctionOptional. Callback when swipe event is triggered. Returns swipe direction as first parameter.
dayShapeStringOptional. Shape of the Day component. Default is circle. Available options are circle and square.
headingLevelNumberOptional. Sets the aria-level for the calendar title heading when on Web. Default is 1.
selectMonthTitleStringOptional. Title of month selector view. Default is Select Month.
selectYearTitleStringOptional. Title of year selector view. Default is Select Year.
dayLabelsWrapperViewStyleOptional. Style for weekdays wrapper. E.g If you want to remove top and bottom divider line.
dayOfWeekStylesTextStyleOptional. Style for changing color and style for any day of the week. E.g If you want all Sundays in RED color, and Mondays in BLUE color, etc. You need to pass JSON object of styles. 0 for Sunday and 6 for Saturday, but if startFromMonday=true, then 0 for Monday and 6 for Sunday. See example below.
monthYearHeaderWrapperStyleViewStyleOptional. Style for header MonthYear title wrapper. E.g If you want to change the order of year and month.

Styles

Some styles will overwrite some won't. For instance:

  • If you provide textStyle with fontFamily and color, out of ranges dates will not apply your color, just fontFamily.

Order of precedence:

  • defaultColor => textStyle => selectedDayColor
  • defaultTodayBackgroundColor => todayBackgroundColor
  • defaultBackgroundColor => selectedDayColor
  • defaultTextStyles => textStyle => selectedDayTextColor

More Examples

Start from Monday, allowRangeSelection, Min and Max Dates and Styles Changes Example

alt tag

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View
} from 'react-native';
import CalendarPicker from 'react-native-calendar-picker';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedStartDate: null,
      selectedEndDate: null,
    };
    this.onDateChange = this.onDateChange.bind(this);
  }

  onDateChange(date, type) {
    if (type === 'END_DATE') {
      this.setState({
        selectedEndDate: date,
      });
    } else {
      this.setState({
        selectedStartDate: date,
        selectedEndDate: null,
      });
    }
  }

  render() {
    const { selectedStartDate, selectedEndDate } = this.state;
    const minDate = new Date(); // Today
    const maxDate = new Date(2017, 6, 3);
    const startDate  =  selectedStartDate ? selectedStartDate.toString() : '';
    const endDate = selectedEndDate ? selectedEndDate.toString() : '';

    return (
      <View style={styles.container}>
        <CalendarPicker
          startFromMonday={true}
          allowRangeSelection={true}
          minDate={minDate}
          maxDate={maxDate}
          todayBackgroundColor="#f2e6ff"
          selectedDayColor="#7300e6"
          selectedDayTextColor="#FFFFFF"
          onDateChange={this.onDateChange}
        />

        <View>
          <Text>SELECTED START DATE:{ startDate }</Text>
          <Text>SELECTED END DATE:{ endDate }</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
    marginTop: 100,
  },
});

Complex Example, Changing Fonts and Colors, Language and etc...

alt tag

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View
} from 'react-native';
import CalendarPicker from 'react-native-calendar-picker';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedStartDate: null,
      selectedEndDate: null,
    };
    this.onDateChange = this.onDateChange.bind(this);
  }

  onDateChange(date, type) {
    if (type === 'END_DATE') {
      this.setState({
        selectedEndDate: date,
      });
    } else {
      this.setState({
        selectedStartDate: date,
        selectedEndDate: null,
      });
    }
  }

  render() {
    const { selectedStartDate, selectedEndDate } = this.state;
    const minDate = new Date(); // Today
    const maxDate = new Date(2017, 6, 3);
    const startDate  =  selectedStartDate ? selectedStartDate.toString() : '';
    const endDate = selectedEndDate ? selectedEndDate.toString() : '';

    return (
      <View style={styles.container}>
        <CalendarPicker
          startFromMonday={true}
          allowRangeSelection={true}
          minDate={minDate}
          maxDate={maxDate}
          weekdays={['Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab', 'Dom']}
          months={['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']}
          previousTitle="Anterior"
          nextTitle="Próximo"
          todayBackgroundColor="#e6ffe6"
          selectedDayColor="#66ff33"
          selectedDayTextColor="#000000"
          scaleFactor={375}
          textStyle={{
            fontFamily: 'Cochin',
            color: '#000000',
          }}
          onDateChange={this.onDateChange}
        />

        <View>
          <Text>SELECTED START DATE:{ startDate }</Text>
          <Text>SELECTED END DATE:{ endDate }</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
    marginTop: 100,
  },
});

Custom styling individual dates

alt tag


let today = moment();
let day = today.clone().startOf('month');
let customDatesStyles = [];
while(day.add(1, 'day').isSame(today, 'month')) {
  customDatesStyles.push({
    date: day.clone(),
    // Random colors
    style: {backgroundColor: '#'+('#00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6)},
    textStyle: {color: 'black'}, // sets the font color
    containerStyle: [], // extra styling for day container
  });
}

render() {
  return (
    <CalendarPicker
      todayTextStyle={{fontWeight: 'bold'}}
      todayBackgroundColor={'transparent'}
      customDatesStyles={customDatesStyles}
      minDate={today}
    />
  );
}

Styling individual weekdays


<CalendarPicker
      textStyle={styles.calendarTextStyle}
      weekdays={CALENDAR_WEEK_DAYS}
      allowRangeSelection
      previousTitle="<"
      previousTitleStyle={{color: '#fff'}}
      nextTitle=">"
      nextTitleStyle={{color: '#f00'}}
      dayLabelsWrapper={{
        borderBottomWidth: 0,
        borderTopWidth: 0,
      }}
      dayOfWeekStyles={{
        0: {
          color: '#00f',
          fontSize: 22,
          fontWeight: 'bold',
          backgroundColor: '#ff0',
        },
        5: {
          color: '#000',
          fontSize: 22,
        },
      }}
    />

Methods

These internal methods may be accessed through a ref to the CalendarPicker.

NameParamsDescription
handleOnPressDayday (Integer)Programmatically select date. day is a number that is the day of the current month. Moment example for today's day of month: moment().date()
handleOnPressNextProgrammatically advance to next month.
handleOnPressPreviousProgrammatically advance to previous month.
resetSelectionsClear date selections. Useful for resetting date range selection when user has picked a start date but not an end date.

TypeScript

Definitions are available at https://www.npmjs.com/package/@types/react-native-calendar-picker courtesy of automatensalat.

npm install --save @types/react-native-calendar-picker

Suggestions?

Open Issues. Submit PRs.

Special Thanks

I would like to call out some contributors who have been helping with this project

Sample Application

The sample app is an Expo project created with create-react-native-app.

cd example
npm run cp
npm install
npm start

Development

The source files are copied from the project root directory into example/node_modules using npm run cp. If a source file is modified, it must be copied over again with npm run cp.

Keywords

FAQs

Package last updated on 09 Jun 2020

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