Home > OS >  Getting the ID of @react-native-community/datetimepicker
Getting the ID of @react-native-community/datetimepicker

Time:11-23

I'm using multiple @react-native-community/datetimepicker's in my component and they both call the same function when the user picks a date.

How do I get the ID or name of the datetimepicker the user has used? I checked but was not able to find the ID or name property. This is what the date picker looks like:

<DateTimePicker
   testID="myDate1"
   value={myDateValue}
   mode="date"
   display="default"
   onChange={this.onCalendarDateChange} />

And this is the function that gets called when the user selects a date:

onCalendarDateChange(event, selectedDate) {

   const id = event.???
}

CodePudding user response:

Based on its the document event is an object with two keys

 const event: AndroidEvent = {
        type: 'set',
        nativeEvent: {},
      };

it does not return any ID to catch it

CodePudding user response:

After working with this package a while, I realized, the idea is to have a single datetimepicker in a form which is why there's no way to retrieve the ID of the picker.

The simple solution I came up with, which works nicely, is to capture the name of the form field for which the datetimepicker is collecting data when I make it visible.

In my case, I have two form fields for which I needed a datetimepicker i.e. startDate and endDate and initially I was trying to use two separate datetimepicker's in my form. This is completely unnecessary.

I now use a single datetimepicker and when the user clicks the calendar icon to show the datetimepicker, I set the name of the form field i.e. startDate or endDate in the state. Once the user selects a date, the onCalendarDateChange() gets called and I simply read from the state whether it's startDate or endDate field that invoked the datetimepicker.

So anyone who needs a datetimepicker for multiple form fields can simply use a single datetimepicker to get the job done using my or a similar approach.

  • Related