0

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');
    }
  };

2 Answers 2

2

As the error says, the problem is that the ref could be null — and in fact, that's what you're initializing it to. That means formRef.current may be null. Which means formRef.current.checkValidity() needs a check for whether formRef.current is null.

You can use &&:

if (formRef.current && formRef.current.checkValidity()) {
//  ^^^^^^^^^^^^^^^^^^^

or the new optional chaining operator:

if (formRef.current?.checkValidity()) {
//                 ^

Side note: There's almost¹ never any reason for === true or === false, and certainly none above. checkValidity returns a boolean, so you already have a boolean to test with the if.

// Idiomatically:
if (x) {  // Is this true?
    // ...
}

if (!x) { // Is this false?
    // ...
}

¹ "almost" - The only time it really makes sense is if what you're testing may not be a boolean at all and you want the check to result in false if it isn't, which is a rare edge case.

Sign up to request clarification or add additional context in comments.

Comments

0

You must somehow ensure formRef.current is not null, because it could be. One way is to add this in the beginning of the callback:

if(!formRef.current) return

Also you could use the optional chaining operator, although in this case if formRef.current turns out to be null, the DO NOTHING part of code will be triggered

if(formRef.current?.checkValidity() === true) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.