How to fix the date[] is not assignable to type [date?, date?] in react hook

2.2k Views Asked by At

What I'm trying to do is to set a date on date range but there's an error which is

Type 'Date[]' is not assignable to type '[Date?, Date?]'.

Types of property 'length' are incompatible.

Type 'number' is not assignable to type '0 | 1 | 2'

code:

const [ dateRange, setDateRange] = useState([new Date('2017-02-01'), new Date('2017-05-20')]);
<DateRangePicker
                    value={dateRange}
                    onChange={value => {
                        this.setState({ value });
                        console.log(value);
                    }} />
2

There are 2 best solutions below

0
On BEST ANSWER

The right way is to import the valuetype from rsuite

import {ValueType} from "rsuite/lib/DateRangePicker";

Then define it in your useState

const [ dateRange, setDateRange] = useState<ValueType>([new Date('2017-02-01'), new Date('2017-05-20')])

<DateRangePicker
    value={dateRange}
    onChange={value => {
    setDateRange(value);
    }}
/>      
2
On

The easiest but not "right" way just to make cast

this.setState({ value: value as [Date?, Date?]});

or

onChange={value:[Date, Date] => {

Better to create [Date?, Date?] variable inside your onChange function using the input value variable