I am new to React Native and am simply looking to have a DatePickerIOS component slide up from the bottom of the screen when a TextInput is touched.
Can someone please point me in the right direction or give me a simple example?
Below is my component. It is very simple. I'm trying to get either the keyboard or the DatePickerIOS to open once the user touches the TextInput.
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
TextInput,
View,
DatePickerIOS
} from 'react-native';
class AddChildVisit extends Component {
render() {
return (
<View>
<Text>Visit Date</Text>
<TextInput
style={{height: 40, width: 300, padding: 4, borderColor: 'gray', borderWidth: 1}}
keyboardType= 'numeric'
/>
<DatePickerIOS
date={new Date()}
mode="date"
/>
</View>
);
}
}
module.exports = AddChildVisit;
I am using DatePickerIOS, here is example how would I do it:
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
TouchableOpacity,
TextInput,
View,
DatePickerIOS
} from "react-native";
var moment = require('moment');
class AddChildVisit extends Component {
constructor(props) {
super(props);
this.state = {
date: new Date(),
showDatePicker: false
}
}
render() {
var showDatePicker = this.state.showDatePicker ?
<DatePickerIOS
style={{ height: 150 }}
date={this.state.date} onDateChange={(date)=>this.setState({date})}
mode="date"/> : <View />
return (
<View>
<Text>Visit Date</Text>
<TouchableOpacity style={{height: 40, width: 300, padding: 4, borderColor: 'gray', borderWidth: 1}}
onPress={() => this.setState({showDatePicker: !this.state.showDatePicker})}>
<Text>{moment(this.state.date).format('DD/MM/YYYY')}</Text>
</TouchableOpacity>
{showDatePicker}
</View>
);
}
}
module.exports = AddChildVisit;
When you press TouchableOpacity, datepicker will show because you trigger flag to show it, and if you press it again, it will close. I also use moment to print date because I was getting error that I can't put object in text component etc. For this example to work you need to install moment, you can do it like this: npm install moment --save
, I already used it in code example above, you can see var moment = require('moment')
, and again in printing date in text {moment(this.state.date).format('DD/MM/YYYY')}
. If you don't want to install/use it, just remove lines with moment from my example - but your date won't be printed then. I'm not really sure how would I call date picker with TextInput because it has to trigger keyboard, and when I have date picker I don't really need keyboard. I hope it helps :)
Another way is using the package react-native-datepicker and works on both platforms Android/iOS https://www.npmjs.com/package/react-native-datepicker
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