Home > database >  EmailJS with typescript giving ref type error - expected type comes from property 'ref'
EmailJS with typescript giving ref type error - expected type comes from property 'ref'

Time:08-12

I am using react typescript and EmailJS for a form. I have copied the documentation code but I am getting a ref type error. Below is the code and then I have shown the error.

ref={form} is giving the error. This and the state declaration are probably the only lines related to the error.

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

export const ContactUs = () => {
  const form = useRef();

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

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

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

(property) React.ClassAttributes.ref?: React.LegacyRef | undefined

Type 'MutableRefObject' is not assignable to type 'LegacyRef | undefined'. Type 'MutableRefObject' is not assignable to type 'RefObject'. Types of property 'current' are incompatible. Type 'undefined' is not assignable to type 'HTMLFormElement | null'.ts(2322)

index.d.ts(137, 9): The expected type comes from property 'ref' which is declared here on type 'DetailedHTMLProps<FormHTMLAttributes, HTMLFormElement>'

CodePudding user response:

Create the ref like this:

const form = useRef(null) // add null here

If it doesn't fix it, check if there are conflicting versions of @types/react. React 18 has breaking changes that could generate TS errors with third-party libraries that haven't been updated yet.

  • Related