HOW TO: React Native Date Picker

React Native Community has a date and time picker for Android and iOS. This component replaces and merges the now deprecated DatePickerIOSTimePickerAndroid and DatePickerAndroid.

In this article, I will explain how to use DateTimePicker and how to fix a major UI issue it presents when trying to keep consistent UI across Android and iOS.

To get in-Depth knowledge on React you can Enroll for a live demo on Reactjs Online Training

Install

Install with npm using:

npm install @react-native-community/datetimepicker --save
cd ios
pod update

Android should auto link if you are using RN v60+

Display

Displaying a Date Picker is pretty straight forward:

import React, { Component } from 'react';
import DateTimePicker from '@react-native-community/datetimepicker';

export default class App extends Component {
  state = {
    date: new Date(),
  }

  render() {
    const { date } = this.state;

    return (
      <DateTimePicker 
        value={ date }
        mode='default'
        display='default'
        onChange={ date => this.setState({ date }) } />
    );
  }
}

The main problem I have with this DatePicker is that Android opens a modal while iOS displays a large scroll wheel (as shown above). This is a drastic difference in UI that needs to be handled. To address this, I made a custom DatePicker component that opens the iOS DatePicker as a modal (shown below).

Take your career to new heights of success with Reactjs Training

I’m using styled-components instead of a style sheet.

import React from 'react';
import { TouchableOpacity, Platform, Text } from 'react-native';
import styled from 'styled-components';
import DateTimePicker from '@react-native-community/datetimepicker';
const Container = styled.TouchableOpacity`
  background-color: ${Platform.OS === 'ios' ? '#00000066' : 'transparent'};
  position: absolute;
  justify-content: flex-end;
  width: 100%;
  height: 100%;
`;
const Header = styled.View`
  width: 100%;
  padding: 16px;
  justify-content: flex-end;
  align-items: flex-end;
  background-color: white;
  border-bottom-width: 1;
  border-color: grey;
`;
export default class DatePicker extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      date: new Date(this.props.date),
    };
  }
  
  render() {
    const { onClose, onChange } = this.props;
    const { date } = this.state;
    return (
      <Container onPress={onClose}>
        {Platform.OS === 'ios' && (
          <Header>
            <TouchableOpacity onPress={onClose}>
              <Text>Done</Text>
            </TouchableOpacity>
          </Header>
        )}
        <DateTimePicker
          value={date}
          mode="date"
          display="default"
          onChange={(e, d) => {
            if (Platform.OS === 'ios') {
              this.setState({ date: d });
              onChange(d);
            } else {
              onClose(d);
            }
         }}
         style={{ backgroundColor: 'white' }}
       />
     </Container>
   );
  }
}

Let’s break down what’s going on here.

{Platform.OS === 'ios' && (
    <Header>
      <TouchableOpacity onPress={onClose}>
        <Text>Done</Text>
      </TouchableOpacity>
    </Header>
  )}

This block displays a header bar on top of the iOS DatePicker. It gives the user a clear way to dismiss the modal but it is not needed for Android.

Get More Info On Reactjs Certification Course

This component takes in three props:

date: this is the initial date the picker will start on
onChange: this method is not required but allows you to respond to date changes. This is iOS only because DateTimePicker only fires an onChange event for Android when the user selects done or cancel.
onClose: this method is called when the modal is closed with the chosen date or undefined if cancelled

You can use this component in one of your screen like:

{this.state.showDatePicker && (
  <DatePicker
    date={this.state.date}
    onClose={date => {
      if (date && Platform.OS !== 'iOS') {
        this.setState({ showDatePicker: false, date: moment(date) });
      } else {
        this.setState({ showDatePicker: false });
      }
    }}
    onChange={d => {
      this.setState({ date: moment(d) });
    }}
  />
)}

showDatePicker state should be set to true when the user selects a your date component which using date state to display the selected date.

You can further customize the DatePicker component to fit your specific requirements or include a time picker.

Jeetendra gautam

My name is Jitendra Gautam I have been working freelancing content writing for last 2 years. Along with this, I am also a skilled web developer. I have been experiencing more than 1 year of web development. I hope you all liked my posts. I will always be grateful for your love and sympathy. Jeetendra Gautam

Leave a Reply