1

I'm new to React and I use the Astro framework. I would like to add a contact form to my landing page and to do so I use the EmailJS service. I tried to get the example in documentation of EmailJS for React and adapt it to Typescript but I can't understand this error:

Type '{ children: any[]; ref: MutableRefObject<string | HTMLFormElement>; onSubmit: (e: any) => void; }' is not assignable to type 'FormHTMLAttributes'. Property 'ref' does not exist on type 'FormHTMLAttributes'.

My code in following:

import ContentSection from "~/components/content-section.astro";
import React, { useRef } from 'react';
import emailjs from '@emailjs/browser';

export const ContactUs = () => {
  const form = useRef() as React.MutableRefObject<string | HTMLFormElement>;

  const sendEmail = (e: any) => {
    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>
  );
};

---

<ContentSection title="Nous contacter" id="contact">
  <Fragment slot="lead">
    Vous avez besoin de <span class="text-primary">renseignements</span> ?
    N'hésitez pas une seconde et contactez-nous !
  </Fragment>
  <div class="max-w-6xl space-y-2">
    <ContactUs />
  </div>
</ContentSection>

Thanks for help, Regards.

Collembole
  • 158
  • 2
  • 13

1 Answers1

0

Maybe having the same name for the ref as the HTML element is overriding its type declaration.

Try changing form to something like formRef, and see if it fixes the type issue.

export const ContactUs = () => {
    const formRef = useRef<HTMLFormElement>(null);
    ..
    ..
    return (
        <form ref={formRef} onSubmit={sendEmail}>
          ..
        </form>
    );
}
Badal Saibo
  • 2,499
  • 11
  • 23
  • I change null by '' because null was not accepted. But I still have the same error with the ref attribute underlined – Collembole May 11 '23 at 17:05