I'm having an issue with Typescript and it's giving me the following error listed below. The part of const formRef = useRef<HTMLFormElement>(null); seems to be good, but the issue looks to be with formRef.current.checkValidity().
How can I add the Typescript typing/get rid of the error?
Error:
(property) React.RefObject<HTMLFormElement>.current: HTMLFormElement | null
Object is possibly 'null'.ts(2531)
Code:
// React Hooks: Refs
const formRef = useRef<HTMLFormElement>(null);
// Send Verification Code
const sendVerificationCode = (event: any) => {
// Event: Cancels Event (Stops HTML Default Form Submit)
event.preventDefault();
// Event: Prevents Event Bubbling To Parent Elements
event.stopPropagation();
// const reference = <HTMLFormElement>formRef.current;
console.log('WHY IS THE FORM VALID???');
console.log(formRef.current.checkValidity());
// Check Form Validity
if (formRef.current.checkValidity() === true) {
// Validate Form
setValidated(true);
// Redux: Send Verification Code Request
dispatch(sendVerificationCodeRequest(email));
}
else {
// Do Nothing (Form.Control.Feedback Will Appear)
console.log('DO NOTHING');
}
};