Open Keyboard and/or DatePickerIOS when TextInput touched in React Native
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 :)