简体   繁体   中英

Using emailjs in react(not typescript)

在此处输入图像描述

在此处输入图像描述

I'm using emailjs library in react. When I submit the form, server is 400 error. First Image public/index.html. Second Image is about the form.

I know that the second argument in the sendForm method is template_id and the last one is user_id. Am I doing something wrong?

I am not understanding why you are adding script in public/index.html . If you are working with React then you don't need to add any script in HTML.

Points to Remember while implementing emailJS in React:

  • Install emailJS and import emailJS from @emailjs/browser
  • Create a Reference using useRef hook.
  • Provide necessary credentials.
  • Use ref in form properly.
  • The name attribute in input element should exactly match with what you're using in emailJS website.

In sendEmail function, I am not seeing any error. I recommend you to recheck html form and follow the code snippet I have attached below.

You can run the following command in terminal to install it.

npm install @emailjs/browser --save

Then you can follow this code snippet to implement.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM