I wanted to add a Date Picker to my form but i got this error Error: TS2345: Argument of type 'Date | null' is not assignable to parameter of type 'string | Date | undefined'. Type 'null' is not assignable to type 'string | Date | undefined'. Can anyone help me to solve it?
export class Form extends React.Component<FormProps, {
fname: string | undefined;
lname: string | undefined;
birthDate: Date | undefined;
}> {
constructor(props: FormProps) {
super(props);
this.state = {
fname: undefined,
lname: undefined,
birthDate: undefined,
};
}
function testField(value: string | undefined | Date, set: React.Dispatch<React.SetStateAction<string | undefined>>): boolean {
if(value === undefined) {
set('');
return false;
}
if(value === '') {
return false;
}
return true;
}
let [fname, setfname] = useState<string | undefined>(undefined);
let [lsname, setlname] = useState<string | undefined>(undefined);
let [birthDate, setBirthDate] = useState<Date | null>(null);
const testNext = () => {
let success = true;
success = testField(fname, setFname) && success;
success = testField(lname, setlname) && success;
success = testField(birthDate, setBirthDate) && success;
return (<Fragment>
<div className="content__form">
<div className="formcolcontainer">
<div className="formcol">
<Input onChange={setFname} name="Fname" error={Fname=== ''}/>
<Input onChange={setlname} name="lname" error={lname=== ''}/>
</div>
<div className="formcol">
<DatePicker
id='BirthDate'
selected={birthDate}
onChange={(date) => setBirthDate(date)}
placeholderText="Birth Date"
/>
</div>
</div>
</div>
</Fragment>);}
CodePudding user response:
DatePicker doesn't want null in the 'selected' prop and your birthDate useState is null, you can leave the default value for birthDate empty. And you should use const for React Hooks.
So:
const [birthDate, setBirthDate] = useState<Date>();
CodePudding user response:
It says that, you described your date state variable as can be null or date. However, it can also be undefined type. You can update your date state to this useState<Date|string|undefined>.
Alternatively, you can hover over to onChange props of DatePicker to see the type of "date" param has. Then you update your state type accordingly.
const [birthDate, setBirthDate] = useState<Date | null | undefined>(null);
