how to open DatePicker on Button Click in React Native

I am using react-native-datepicker and the following logic:

<DatePicker
showIcon={false}
hideText={true}
ref={(ref)=>this.datePickerRef=ref}
...
/>

and from your element:

onPress={() => this.datePickerRef.onPressDate()}

You can simply have flag whether render picker component or not and switch it on Press. Something like this

render() {
  return (
    <View>
      <TouchableOpacity
        onPress={() => this.setState({ picker: !this.state.picker })}>
        <Text>Hello Date</Text>
      </TouchableOpacity>
      {this.renderPicker()}
    </View>
  );
}

renderPicker() {
  if (this.state.picker) {
    return (
      <DatePicker
        style={{ width: 200 }}
        ref={picker => {
          this.datePicker = picker;
        }}
        date={this.state.date}
        mode="date"
        placeholder="Select date"
        format="YYYY-MM-DD"
        minDate="2016-05-01"
        maxDate="2020-12-12"
        confirmBtnText="OK"
        cancelBtnText="Cancel"
        onDateChange={date => {
          this.setState({ date: date });
        }}
      />
    );
  }
}

I Suggest to use react-native-datepicker library for Date Picker. It will give you more customizing options and is compatible with both platforms i.e Android and iOS.

Below is the sample code that i have used in one of my application:-

<View style={{ backgroundColor: 'transparent', margin: 5 }}>
            <DatePicker date={this.state.date} showIcon={false} placeholder="Birthday" mode="date" format="DD-MM-YYYY"
              customStyles={{
                dateInput: {
                  borderWidth: 0,
                  height: 50,
                  width: 170,
                  right: 30,
                },
                dateText: {
                  marginTop: 5,
                  color: 'white',
                  fontSize: 18,
                },
                placeholderText: {
                  marginTop: 5,
                  right: 10,
                  color: 'white',
                  fontSize: 18,
                }
              }
              }
              onDateChange={(date) => { this.setState({ date: date }) }} placeholderTextColor="white" underlineColorAndroid={'rgba(0,0,0,0)'} style={{ height: 50, width: 170, paddingLeft: 15, borderRadius: 4, backgroundColor: 'rgba(0,0,0,0.4)' }}></DatePicker>
          </View>

You can find the library HERE

Tags:

React Native