Implementing a Date Time picker in React Native (2021)

Last updated on December 28, 2020 A Goodman Loading... 2 comments

In the old days, DatePickerIOS, DatePickerAndroid, and TimePickerAndroid components used to be used to create Date and Time pickers in React Native applications but nowadays, these ones are deprecated.

In the year 2021, using react-native-datetimepicker/datetimepicker is a neat and elegant approach to implement a Date and Time picker for both iOS and Android.

Note: This package is still published on npmjs.com under the old namespace (@react-native-community) but will be published under a new namespace soon, with a major version bump. We will update this article as soon as this happens.

Let’s take a look at the datetimepicker module’s options and explore a complete example of using it.

Installation

Add the module to your project by running:

npm i @react-native-community/datetimepicker

Or:

yarn add @react-native-community/datetimepicker

If you’re building an app for iOS then run the following command to link the dependency:

npx pod-install

Options

This table lists the props of the datetimepicker module, and the first 4 properties are used the most.

PropRequirementPlatformDescription
modeoptionalAndroid
iOS
Windows
Defines the type of the picker (“date”, “time”, “datetime” – iOS, “countdown” – iOS)
displayoptionalAndroid
iOS
Windows
Defines the visual display of the picker (“default”, “spinner”, “calendar” – Android, “clock” – Android, “compact” – iOS, “inline” – iOS)
onChangeoptionalAndroid
iOS
Windows
Date change handler that receives the event and the date as parameters.
valuerequiredAndroid
iOS
Windows
Defines the date or time value used in the component
maximumDateoptionalAndroid
iOS
Windows
Defines the maximum date that can be selected
minimumDateoptionalAndroid
iOS
Windows
Defines the minimum date that can be selected
timeZoneOffsetInMinutesoptionaliOSAllows changing of the timeZone of the date picker
timeZoneOffsetInSecondsoptionalWindowsAllows changing of the time zone of the date picker
dayOfWeekFormatoptionalWindowsSets the display format for the day of the week headers
dateFormatoptionalWindowsSets the display format for the date value in the picker’s text box
firstDayOfWeekoptionalWindowsIndicates which day is shown as the first day of the week
textColoroptionaliOSAllows changing of the textColor of the date picker
localeoptionaliOSAllows changing of the locale of the component
is24HouroptionalAndroid
Windows
Allows changing of the time picker to a 24 hour format
neutralButtonLabeloptionalAndroidAllows displaying neutral button on picker dialog
minuteIntervaloptionalAndroid
iOS
Windows
The interval at which minutes can be selected
styleoptionaliOSSets style directly on picker component

By default, the picker height is fixed to 216px. The picker’s text color is controlled by the application theme (light / dark mode). In dark mode, the text is white, and in light mode, the text is black.

A Complete Example

This example contains a text component and a button. When the button is pressed, a Date picker will show up and let the user pick a date from it. That date will be displayed within the text component.

Preview:

The code:

// App.js
import React, {useState} from 'react';
import {StyleSheet, View, Text, Button, Platform} from 'react-native';

import DateTimePicker from '@react-native-community/datetimepicker';

const App = () => {
  const [isPickerShow, setIsPickerShow] = useState(false);
  const [date, setDate] = useState(new Date(Date.now()));

  const showPicker = () => {
    setIsPickerShow(true);
  };

  const onChange = (event, value) => {
    setDate(value);
    if (Platform.OS === 'android') {
      setIsPickerShow(false);
    }
  };

  return (
    <View style={styles.container}>
      {/* Display the selected date */}
      <View style={styles.pickedDateContainer}>
        <Text style={styles.pickedDate}>{date.toUTCString()}</Text>
      </View>

      {/* The button that used to trigger the date picker */}
      {!isPickerShow && (
        <View style={styles.btnContainer}>
          <Button title="Show Picker" color="purple" onPress={showPicker} />
        </View>
      )}

      {/* The date picker */}
      {isPickerShow && (
        <DateTimePicker
          value={date}
          mode={'date'}
          display={Platform.OS === 'ios' ? 'spinner' : 'default'}
          is24Hour={true}
          onChange={onChange}
          style={styles.datePicker}
        />
      )}
    </View>
  );
};

// just add some styles to make our app look more beautiful
// This is not the focus of this article
const styles = StyleSheet.create({
  container: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    flex: 1,
    justifyContent: 'center',
    padding: 50,
  },
  pickedDateContainer: {
    padding: 20,
    backgroundColor: '#eee',
    borderRadius: 10,
  },
  pickedDate: {
    fontSize: 18,
    color: 'black',
  },
  btnContainer: {
    padding: 30,
  },
  // This only works on iOS
  datePicker: {
    width: 320,
    height: 260,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'flex-start',
  },
});

export default App;

And here’s my package.json file:

{
  "name": "react_native_2021",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/datetimepicker": "^3.0.8",
    "react": "16.13.1",
    "react-native": "0.63.4"
  },
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/runtime": "^7.8.4",
    "@react-native-community/eslint-config": "^1.1.0",
    "babel-jest": "^25.1.0",
    "eslint": "^6.5.1",
    "jest": "^25.1.0",
    "metro-react-native-babel-preset": "^0.59.0",
    "react-test-renderer": "16.13.1"
  },
  "jest": {
    "preset": "react-native"
  }
}

Conclusion

In this article, we went over how to create a Date and Time Picker in React Native by using the react-native-datetimepicker / datetimepicker module. If you’d like to learn more about React Native, check out our React Native topic page for more tutorials and examples.

Subscribe
Notify of
guest
2 Comments
Inline Feedbacks
View all comments
coder1
coder1
4 months ago

what does Platform.OS === ‘android’ do?

DH2001
DH2001
2 months ago
Reply to  coder1

That checks if the platform in use is android

Related Articles