I am trying to store a date range into an array using DateRangePicker from rsuite. Right now my application works as intended, but I am still getting some errors in Typescript. How do I do this correctly?
import { DateRangePicker } from "rsuite";
const [dateRange, setDateRange] = useState([]);
<DateRangePicker
format="MM/dd/yyyy"
character=" – "
value={dateRange} //value has error
onChange={setDateRange} //onChange has error
/>
Value error: Type ‘never[]’ is not assignable to type ‘[Date, Date]’.
Target requires 2 element(s) but source may have fewer.ts(2322)
onChange error: Type ‘Dispatch<SetStateAction<never[]>>’ is not assignable to type ‘(value: DateRange | null, event: SyntheticEvent<Element, Event>) => void’.
Types of parameters ‘value’ and ‘value’ are incompatible.
Type ‘DateRange | null’ is not assignable to type ‘SetStateAction<never[]>’.
Type ‘null’ is not assignable to type ‘SetStateAction<never[]>’.ts(2322)
I have also tried the following but the "range" in setDate(range)" is also throwing an error
<DateRangePicker
format="MM/dd/yyyy"
character=" – "
onChange={(range) => setDateRange(range)} //2nd range has error
/>
range error: Argument of type ‘DateRange | null’ is not assignable to parameter of type ‘SetStateAction<never[]>’.
Type ‘null’ is not assignable to type ‘SetStateAction<never[]>’.ts(2345)
2
Answers
It looks like you’re facing TypeScript type issues when using the DateRangePicker from rsuite. To resolve these errors, you need to provide appropriate types for the state and the onChange handler. Here’s how you can do it:
1.The useState hook initializes dateRange as a tuple of optional Date types.
2.The handleDateChange function ensures that the value passed to setDateRange is a tuple of two optional Date types or an empty array.
This should resolve the TypeScript errors you’re encountering. Adjust the types and handling according to your specific requirements.
You have to use type which is defined as “
The type of the
value
isValueType
.Check the prop types in the official doc.
Just import the
ValueType
or use the type as[Date?, Date?]
You can check sandbox running example