I wanted to know how we can display datepicker on button click in react native. I have tried various solutions still no success,Any help would be helpful. thank you.
Below is what i tried
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
View,DatePicker
} from 'react-native';
This is my render method
render(){
return(
<TouchableOpacity
onPress={() => this.datePicker.onPressDate()}>
<Text>
Hello Date
</Text>
</TouchableOpacity>
<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})}}
/>
);
}
whenever i run i get below error
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With