Setting up an auto-reply system for your React project can significantly enhance the user experience by providing instant feedback when users submit forms. EmailJS is an excellent service for this use case as it enables you to send emails directly from your client-side app without requiring a dedicated backend. In this article, we’ll explore two ways to integrate EmailJS into your React project: using the SDK and the REST API.
Prerequisites
- A React project setup (using Create React App, Vite, or your preferred framework).
- An EmailJS account. Sign up here.
- A service ID, template ID, and public key from your EmailJS dashboard.
Implementation Using the EmailJS SDK
Step 1) Install the EmailJS SDK
Install the EmailJS SDK using npm or yarn:
npm install --save @emailjs/browser
yarn add @emailjs/browser
Step 2) Configure the SDK
Import and configure the SDK in your React component:
import React from 'react';
import emailjs from '@emailjs/browse';
const AutoReplyForm = () => {
const formRef = React.useRef();
const sendEmail = (e) => {
e.preventDefault();
emailjs
.sendForm(
'YOUR_SERVICE_ID',
'YOUR_TEMPLATE_ID',
formRef.current,
'YOUR_PUBLIC_KEY'
)
.then(
(result) => {
console.log('Success:', result.text);
alert('Email sent successfully!');
},
(error) => {
console.error('Error:', error.text);
alert('Failed to send email.');
}
);
};
return (
<form ref={formRef} onSubmit={sendEmail}>
<input type="text" name="user_name" placeholder="Your Name" required />
<input type="email" name="user_email" placeholder="Your Email" required />
<textarea name="message" placeholder="Your Message" required />
<button type="submit">Send</button>
</form>
);
};
export default AutoReplyForm;
Key Points:
- Replace
YOUR_SERVICE_ID
,YOUR_SERVICE_ID
,YOUR_TEMPLATE_ID
, andYOUR_PUBLIC_KEY
with the credentials from your EmailJS dashboard. - The
sendForm
method automatically parses the form data.
Reference:
Alternative Method: Implementation Using the EmailJS REST API
Step 1) Install Axios
Install Axios for making HTTP requests:
npm install axios
Step 2) Create the REST API Integration
Use Axios to send a POST request to the EmailJS REST endpoint:
import React, { useState } from 'react';
import axios from 'axios';
const AutoReplyForm = () => {
const [formData, setFormData] = useState({
user_name: '',
user_email: '',
message: '',
});
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const sendEmail = async (e) => {
e.preventDefault();
const payload = {
service_id: 'YOUR_SERVICE_ID',
template_id: 'YOUR_TEMPLATE_ID',
user_id: 'YOUR_PUBLIC_KEY',
template_params: formData,
};
try {
const response = await axios.post('https://api.emailjs.com/api/v1.0/email/send', payload);
console.log('Success:', response.data);
alert('Email sent successfully!');
} catch (error) {
console.error('Error:', error);
alert('Failed to send email.');
}
};
return (
<form onSubmit={sendEmail}>
<input
type="text"
name="user_name"
placeholder="Your Name"
value={formData.user_name}
onChange={handleChange}
required
/>
<input
type="email"
name="user_email"
placeholder="Your Email"
value={formData.user_email}
onChange={handleChange}
required
/>
<textarea
name="message"
placeholder="Your Message"
value={formData.message}
onChange={handleChange}
required
/>
<button type="submit">Send</button>
</form>
);
};
export default AutoReplyForm;
Key Points:
- The REST API requires a payload containing
service_id
,template_id
,user_id
, andtemplate_params
. - Replace
YOUR_SERVICE_ID
,YOUR_TEMPLATE_ID
, andYOUR_PUBLIC_KEY
accordingly.
Reference:
Where to Find Those IDs and Keys on EmailJS Dashboard
SERVICE_ID
:
Go to the dashboard → Email Services
tab in the sidebar menu.
TEMPLATE_ID
:
Go to the Email Templates
tab in the sidebar menu and click Create New Template
.
PUBLIC_KEY
:
Go to Account in the top menu bar and choose Generate
tab. You’ll find your Public key
and Private key
in the API keys section.
How to Customize Template
Customize Content:
You will receive this template as a notification when someone sends you the form.
Customize Auto-Reply Message:
This template is what someone will receive once they submit the form.
Note: {{ subject }}
, {{ sender_name }}
, {{ message }}
, {{ email }}
, etc. need to match your variable names in your code.
Conclusion
Both methods provide effective ways to implement an auto-reply system with EmailJS in your React project. The SDK is great for quick setups, while the REST API offers more flexibility for custom implementations. Choose the approach that best suits your project’s requirements.
If you have any questions, feel free to leave comments. Your feedback is always appreciated.
Source link
lol