Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: How do you implement DatePickerAndroid?

According to the RN docs, you have to call an async/await function to open the Android Date Picker. I've tried installing the Async to generator transform Babel preset and adding a .babelrc file with

{ "plugins": ["transform-async-to-generator"] }

but that just seems to throw an unexpected token error when adding any RN component using tags (eg < Image ... /> would throw and unexpected token error). This is what my function to open the Android Date Picker looks like

async openAndroidDatePicker: function() {
  try {
    const {action, year, month, day} = await DatePickerAndroid.open({
      date: new Date()
    });
  } catch ({code, message}) {
    console.warn('Cannot open date picker', message);
  }
}
like image 975
sdfsdf Avatar asked Jul 06 '16 05:07

sdfsdf


People also ask

How do I add a date picker in react native?

import React, {useState} from 'react'; import {View, Button, Platform, SafeAreaView , StyleSheet} from 'reactnative'; import DateTimePicker from '@react-native-community/datetimepicker'; export default function App() { const [mydate, setDate] = useState(new Date()); const [displaymode, setMode] = useState('time'); ...

Which property returned by DatePickerAndroid open helps to check whether date is picked or not?

Returns a Promise which will be invoked an object containing action , year , month (0-11), day if the user picked a date. If the user dismissed the dialog, the Promise will still be resolved with action being DatePickerAndroid.

What is the use of date and picker in Android?

Android DatePicker is a user interface control that is used to select the date by day, month, and year in the android application. DatePicker is used to ensure that the users will select a valid date.


2 Answers

My way without any packages, only using docs DatePickerAndroid and TimePickerAndroid

import components what you need. For me are:

import {
Text,
SafeAreaView,
TouchableOpacity,
View,
Platform,
StatusBar,
DatePickerIOS,
Slider,
DatePickerAndroid,
TimePickerAndroid,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import MainStyles from '../styles/MainStyles';

Then set your state:

constructor(props) {
 super(props);
 this.setDate = this.setDate.bind(this);
 this.state = {
   chosenDate: new Date(),
   chosenAndroidTime: '00:00',
   androidDate: `${new Date().getUTCDate()}/${new Date().getUTCMonth() + 1}/${new Date().getUTCFullYear()}`,
   value: 50,
 };
}

After declarate funcs:

setDate(newDate) {
  this.setState({ chosenDate: newDate });
}

setDateAndroid = async () => {
  try {
    const {
      action, year, month, day,
    } = await DatePickerAndroid.open({
    date: new Date(),
    minDate: new Date(),
    });
    if (action !== DatePickerAndroid.dismissedAction) {
      this.setState({ androidDate: `${day}/${month + 1}/${year}` });
    }
  } catch ({ code, message }) {
    console.warn('Cannot open date picker', message);
  }
};

setTimeAndroid = async () => {
  try {
    const { action, hour, minute } = await TimePickerAndroid.open({
      hour: 14,
      minute: 0,
      is24Hour: false, // Will display '2 PM'
    });
    if (action !== TimePickerAndroid.dismissedAction) {
      // Selected hour (0-23), minute (0-59)
      const m = (minute < 10) ? `0${minute}` : minute;
      const h = (hour < 10) ? `0${hour}` : hour;
      console.log(`time: ${hour}:${minute}`);
      this.setState({ chosenAndroidTime: `${h}:${m}` });
    }
  } catch ({ code, message }) {
    console.warn('Cannot open time picker', message);
  }
};

Finally add to your view container:

       {
          Platform.OS === 'ios' ? (
            <DatePickerIOS
              date={chosenDate}
              onDateChange={this.setDate}
            />
          ) : (
            <View style={MainStyles.AndroidDatePickerWrap}>
              <TouchableOpacity onPress={() => this.setDateAndroid()}>
                <View style={MainStyles.HistoryTime}>
                  <Icon name="ios-calendar" size={25} color="rgb(49, 49, 49)" />
                  <Text style={[MainStyles.HistoryTimeText, { fontSize: 16 }]}>
                    {androidDate}
                  </Text>
                </View>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => this.setTimeAndroid()}>
                <View style={MainStyles.HistoryTime}>
                  <Icon name="ios-time" size={25} color="rgb(49, 49, 49)" />
                  <Text style={[MainStyles.HistoryTimeText, { fontSize: 16 }]}>
                    {chosenAndroidTime}
                  </Text>
                </View>
              </TouchableOpacity>
            </View>
          )
        }

As a result you must see differt picker for iOS and android. This is works for me, hope this will help for you.

like image 155
Serhii Onishchenko Avatar answered Oct 11 '22 14:10

Serhii Onishchenko


Solved. my function's syntax was wrong... this is what worked for me:

async openAndroidDatePicker() {
  try {
    const {action, year, month, day} = await DatePickerAndroid.open({
      date: new Date()
    });
  } catch ({code, message}) {
    console.warn('Cannot open date picker', message);
  }
}

Keep in mind I was using createClass for this examples, not es6 classes.

like image 36
sdfsdf Avatar answered Oct 11 '22 15:10

sdfsdf