Skip to content
Advertisement

Can’t set DateTimePicker’s defaultValue to blank in React JS

I am new to react js. I currently have a web page with the a simple DateTimePicker (the datetimepicker i am using is from react-widgets/lib/). So the idea is I have a variable called myvalue. If it is NOT null, I set the defaultValue of DateTimePicker to myvalue, otherwise – I leave DateTimePicker’s default input value blank.

If myvalue has a value, there is no problem – DateTimePicker displays the value in the input. But, if myvalue is empty and I try to set DateTimePicker input to blank, it throws an error:

Cannot read properties of undefined (reading 'map'): undefined 

This is my code snippet:

function MyDateFunction(props) {
    const { t } = useTranslation();

    return (
        <Field>
            <HorizontalFlex>
                <DateTimePicker
                    defaultValue = { myvalue || ''}
                    
                />
            </HorizontalFlex>
        </Field>
    );
}

Instead of '' I also tried null, new Date() and “”. None of that works :C

Any help much appreciated!

Advertisement

Answer

First of all, I would rather use the the Nullish coalescing operator (??):

defaultValue = { myvalue ?? ''}

This is unless myvalue being null is a valid option, which could be true in your case. In such a case, your check is fine.

In the code snippet you provided, I cannot find any references to myvalue except where you use it; this will cause an error unless the code you provided is a simpler form you tried to get from your original code.

Speaking of default values, I would assume that myvalue is a property of your component. What I would do this case is something like this:

function MyDateFunction({myvalue = ''}) {

Even with this pattern you have to be careful when switching between controlled and uncontrolled components, given that the DateTimePicker will be uncontrolled.

Finally, which is the main reason behind your question, The error is related to using the DateTimePicker API. It will be helpful to provide its NPM page. Mainly, it seems that defaultValue cannot be an empty string, native date, or null value; you tried all. This is unless there is something more with the API call.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement