2

Is there a way to close a previously opened instance of @react-native-community/datetimepicker? I'd like to close it in componentWillUnmount or using setTimeout or some other event. Unfortunately, even if the component is removed, the native picker stays open. I tried something like this:

function example() {
  const [showPicker, setShowPicker] = useState(false);

  setTimeout(() => {
    setShowPicker(!showPicker);
  }, 5000);

  return (
    <>
      {showPicker && (
        <DateTimePicker mode="date" value={new Date()} />
      )}
    </>
  );
}

This makes the picker open every 10 seconds but it needs to be closed manually. Is there any way to close it directly from the code (not by the user)?

TJ82
  • 51
  • 4

2 Answers2

0

Try this might help

import React, { useEffect } from 'react'

function example() {
  
  const [showPicker, setShowPicker] = useState(false);

  useEffect(() => {
     setShowPicker(true);

     // returned function will be called on component unmount 
     return () => {
       setShowPicker(false)
     }
  }, []);    

  return (
    <>
      {showPicker && (
        <DateTimePicker mode="date" value={new Date()} />
      )}
    </>
  );
}

You can check ComponentWillMount in Hooks

Nooruddin Lakhani
  • 7,507
  • 2
  • 19
  • 39
  • 1
    You don't understand. The calendar doesn't disappear even if the component is unmounted. It is a native popup and there seems to be no way of closing it. – TJ82 Oct 27 '20 at 21:03
  • Closing way is just when you changes in state and make showPicker to false so it will hide the picker from component . It's already in example also – Nooruddin Lakhani Oct 28 '20 at 04:29
  • Just try to change showPicker to false in state then check. It will surely remove from component – Nooruddin Lakhani Oct 28 '20 at 04:30
0

The other solution didn't work for me so I had to use a workaround as shown below. I used two separate DateTimePickers so when a new date is selected it hides the first and shows the second, and vice versa.

State definitions:

const [date, setDate] = useState(new Date());
const [showFirstPicker, setShowFirstPicker] = useState(true);
const [showSecondPicker, setShowSecondPicker] = useState(false);

State change functions:

const changeFirstPicker = (event, selectedDate) => {
    setShowFirstPicker(false);
    setDate(selectedDate);
    setShowSecondPicker(true);
}

const changeSecondPicker = (event, selectedDate) => {
    setShowSecondPicker(false);
    setDate(selectedDate);
    setShowFirstPicker(true);
}

Date Pickers:

{showFirstPicker && (
    <DateTimePicker
        value={date}
        mode="date"
        is24Hour={true}
        display="default"
        onChange={changeFirstPicker}
    />      
)}
                
{showSecondPicker && (
    <DateTimePicker
        value={date}
        mode="date"
        is24Hour={true}
        display="default"
        onChange={changeSecondPicker}
    /> 
)}