Home > Back-end >  HTMLFormElement null is not assignable to parameter of type string | Typescript | EmailJS
HTMLFormElement null is not assignable to parameter of type string | Typescript | EmailJS

Time:06-29

React Typescript is prevent me from being able to use the boilerplate code from emailJS.

I have modified the boiler plate code to fix one error on the UseRef() and const sendEmail.

I am getting the error on the form.current line in function sendForm().

Error: (property) React.RefObject.current: HTMLFormElement | null

Argument of type 'HTMLFormElement | null' is not assignable to parameter of type 'string | HTMLFormElement'. Type 'null' is not assignable to type 'string | HTMLFormElement'.ts(2345)

import React, { useRef } from 'react';
import emailjs from '@emailjs/browser';

export const ContactUs = () => {
  const form = useRef<HTMLFormElement>(null);

  const sendEmail = (e) => {
    e.preventDefault();

    emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', form.current, 'YOUR_PUBLIC_KEY')
      .then((result) => {
          console.log(result.text);
      }, (error) => {
          console.log(error.text);
      });
  };

  return (
    <form ref={form} onSubmit={sendEmail}>
      <label>Name</label>
      <input type="text" name="user_name" />
      <label>Email</label>
      <input type="email" name="user_email" />
      <label>Message</label>
      <textarea name="message" />
      <input type="submit" value="Send" />
    </form>
  );
};

CodePudding user response:

This kind of error is why I love TypeScript ;)

The compiler is smart enough to understand that form.current can contain a form, or it could be null, so it is typed as HTMLFormElement | null.

In your sendEmail function you are not accounting for this case in any way, so the compiler is yelling and whining and is completely right!

You must account for the case in which form.current is null:

  const sendEmail = (e) => {
    e.preventDefault();

    const currentForm = form.current;
    // this prevents sending emails if there is no form.
    // in case currentForm cannot possibly ever be null,
    // you could alert the user or throw an Error, here
    if (currentForm == null) return;

    // the compiler is smart enough to know that currentForm here is of type HTMLFormElement 
    emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', currentForm, 'YOUR_PUBLIC_KEY')
      .then((result) => {
          console.log(result.text);
      }, (error) => {
          console.log(error.text);
      });
  };
  • Related