Reputation: 9411
I have a following React + Material DatePicker code, reproduced literally from the respective documentation.
let App: React.FC = () => {
const [dateStart, handleDateStart] = useState(new Date());
const [dateEnd, handleDateEnd] = useState(new Date());
return (
// Pickers from Material https://material-ui-pickers.dev/getting-started/usage
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<DateTimePicker value={dateStart} onChange={handleDateStart}/>
<DateTimePicker value={dateEnd} onChange={handleDateEnd}/>)
</MuiPickersUtilsProvider>);
};
However, I write in TypeScript and it complains on the onChange bits:
Error:(28, 47) TS2322: Type 'Dispatch<SetStateAction<Date>>' is not assignable to type '(date: MaterialUiPickersDate) => void'.
Types of parameters 'value' and 'date' are incompatible.
Type 'MaterialUiPickersDate' is not assignable to type 'SetStateAction<Date>'.
Type 'null' is not assignable to type 'SetStateAction<Date>'.
TsConfig:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}
I am new to React and Material, how can I avoid this error?
Upvotes: 8
Views: 12693
Reputation: 101
For me it helped to set my type to this:
startsAt: Date | Moment | null;
Upvotes: 3
Reputation: 41
Import MaterialUiPickersDate
import { MaterialUiPickersDate } from '@material-ui/pickers/typings/date';
Working Example
import { DateTimePicker, MuiPickersUtilsProvider } from '@material-ui/pickers';
import React, { useState } from 'react';
import DateFnsUtils from '@date-io/date-fns';
import { MaterialUiPickersDate } from '@material-ui/pickers/typings/date';
interface IDateTimePickerComponent {
label: string;
}
function DateTimePickerComponent({ label }: IDateTimePickerComponent) {
const [selectedDate, handleDateChange] =
useState<MaterialUiPickersDate | null>(new Date());
return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<DateTimePicker
disablePast
label={label}
value={selectedDate}
onChange={handleDateChange}
/>
</MuiPickersUtilsProvider>
);
}
export default DateTimePickerComponent;
Upvotes: 4
Reputation: 3616
The problem is that datepicker can return null
as well (in case value is empty)
Working example:
const [date, setDate] = React.useState<Date | null>(new Date());
return (
<DatePicker
value={date}
onChange={newDate => setDate(newDate)}
/>
)
Upvotes: 13
Reputation: 731
try useState<Date>(new Date())
to prevent error check type of typescript
Upvotes: 0