Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set null for DateTimePicker

I'm using DateTimePicker(@react-native-community/datetimepicker).

How to set null as default value for DateTimePicker?

Because in the first time , value of DateTimePicker should be null. When I set it to null ,get the following error :

Invariant Violation: A date or time should be specified as 'value'.

 <DateTimePicker
     testID="dateTimePicker"
     timeZoneOffsetInMinutes={0}
     value={null}
     mode='date'
     is24Hour={true}
     display="default"
     onChange={onChange}
  />

2 Answers

This post is a year old but I will answer to help other programmers.

You can initialize the state to null if the datepicker has not rendered in the page. You could have a state or hook that affects the visibility of your picker.

const [pickerVis, setPickerVis] = useState(false);
const [date, setDate] = useState(null);

Then with the use of a button/pressable/checkbox/Touchable etc you can use:

onChange={() => { setDate(new Date()); setPickerVis(true)}}

Then finally have an conditional render on the page like so:

{pickerVis === true && (<View><DateTimePicker
testID="dateTimePicker"
timeZoneOffsetInMinutes={0}
value={date}
mode='date'
is24Hour={true}
display="default"
onChange={onChange}
/> </View>)}
like image 120
acetaminoCode Avatar answered Nov 30 '25 23:11

acetaminoCode


You should verify is your date is null on your onChange method

<DateTimePicker
        value={date}
        mode='date'
        onChange={(date) => {
            **if (date) setDate(date)** //This is your validation
            setShowDatePicker(false)
        }}
/>
like image 20
Alan Neres Avatar answered Dec 01 '25 00:12

Alan Neres



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!