Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically open/close react-native-datetimepicker?

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.

like image 998
Bertrand Caron Avatar asked Sep 10 '26 10:09

Bertrand Caron


1 Answers

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.

like image 60
Bala Vigness Avatar answered Sep 13 '26 00:09

Bala Vigness



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!