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?
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)}
/>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With