Is there a way to programmatically open/close the date picker from react-native-datetimepicker?
My use case is creating a component based on TouchableOpacity that opens the DatePicker when pressed (with a much bigger surface area than the tiny date picker).
RNDateTimePicker does not seem to accept a ref, nor to have an API to hide/show.
Thank you very much.
Here comes the magic of state .Try doing this,
import React, { useState } from 'react';
import { TouchableOpacity, Text } from 'react-native';
import DateTimePicker from 'react-native-datetimepicker';
const CustomDateTimePicker = () => {
const [showPicker, setShowPicker] = useState(false);
const [selectedDate, setSelectedDate] = useState(new Date());
const handlePickerOpen = () => {
setShowPicker(true);
};
const handlePickerClose = () => {
setShowPicker(false);
};
const handleDateChange = (event, date) => {
if (date !== undefined) {
setSelectedDate(date);
// Do something with the selected date
}
setShowPicker(false);
};
return (
<>
<TouchableOpacity onPress={handlePickerOpen}>
<Text>Open Date Picker</Text>
</TouchableOpacity>
{showPicker && (
<DateTimePicker
value={selectedDate}
mode="date"
onChange={handleDateChange}
/>
)}
</>
);
};
export default CustomDateTimePicker;
By using the state variables , We can make the state to true or false as we desired.
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