React Native DatePickerAndroid Example

This is my example of DatePickerAndroid in a React Native application.

react native datepickerandroid example

If you don’t have a project already start a new one by issuing

react-native init datepicker

First let create a simple button. Container’s style is just to have the button centered in the middle of the screen.

import React, {Component} from 'react';
import {Button, StyleSheet, Text, View} from 'react-native';

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Button title="Pick a date" />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  }
});

Next step is to add the import.

import {Button, StyleSheet, DatePickerAndroid, View} from 'react-native';

Step 3 in our React Native DatePickerAndroid example is declaring some objects in the state that will represent the date and the text displayed.

Add this code in the class. dateText will be used everywhere we need a textual representation of our date.

constructor() {
    super();
    this.state = {
      date: new Date(),
      dateText: 'Pick a date'
    }
}

Now for the magic. Add this function that will open the date picker dialog for us.

  • Why it has async keyword before? Read more about async/await here.
  • {action, year, month, day} are objects from the promise returned by the open function of the DatePickerAndroid.
  • options param is an object containing the following keys (you will see below I send only the {date: {}} param in it).
  • We compose a new date using info from the picker then create a new state (object) with the same keys as our state and call this.setState which will cause react to re-render the interface with the new data.
showDatePicker = async (options) => {
    try {
      const {action, year, month, day} = await DatePickerAndroid.open(options);
      if (action !== DatePickerAndroid.dismissedAction) {
        let date = new Date(year, month, day);
        let newState = {};
        newState['date'] = date;
        newState['dateText'] = date.toLocaleDateString("en-US");
        this.setState(newState);
      }
    } catch ({code, message}) {
      console.warn(`error `, code, message);
    }
};

But it’s not over yet, two more things need to be done for this DatePickerAndroid example of React Native to work.

  1. bind the showDatePicker function
  2. call it

We need to bind this to the showDatePicker function so this.setState inside it knows what to do. See this stackoverflow question for a better explanation.

constructor() {
    super();
    this.state = {
      date: new Date(),
      dateText: 'Pick a date'
    }
    this.showDatePicker.bind(this);
}

Lastly add an onPress action to the button. This will get called when we press the button. Notice we pass an object containing a date key. This is the date required by DatePickerAndroid.open function. (I was talking about this above).

Here we are using the date from the state which opens the picker to the current date but obviously you can tweak it to display any other date.

<Button title={this.state.dateText} onPress={() => this.showDatePicker({date: this.state.date})}/>
Full code
import React, {Component} from 'react';
import {Button, StyleSheet, DatePickerAndroid, View} from 'react-native';

export default class App extends Component {

  constructor() {
    super();
    this.state = {
      date: new Date(),
      dateText: 'Pick a date'
    }
    this.showDatePicker.bind(this);
  }

  showDatePicker = async (options) => {
    try {
      const {action, year, month, day} = await DatePickerAndroid.open(options);
      if (action !== DatePickerAndroid.dismissedAction) {
        let date = new Date(year, month, day);
        let newState = {};
        newState['date'] = date;
        newState['dateText'] = date.toLocaleDateString("en-US");
        this.setState(newState);
      }
    } catch ({code, message}) {
      console.warn(`error `, code, message);
    }
  };

  render() {
    return (
      <View style={styles.container}>
        <Button title={this.state.dateText} onPress={() => this.showDatePicker({date: this.state.date})}/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  }
});
FacebookTwitterLinkedin