Sending email in react js - reactjs

I am new to react. I need to know how to send a mail in react. There is no forms.
When I search in google, everything comes with a form fill up.
I just need a simple function, that triggers to send mail.
Can anyone help with that?

** Used EmailJs https://www.emailjs.com/ here to get the message from the user.**
import emailjs from '#emailjs/browser';
import React, { useRef } from 'react';
function ContactForm() {
const form = useRef();
//console.log('Hello');
const sendEmail = (e) => {
e.preventDefault();
emailjs.sendForm('****', 'template_****', form.current, '****')
.then((result) => {
console.log(result.text);
alert('Message sending successfully!');
form = "";
}, (error) => {
console.log(error.text);
});
};
<div>
<h4>inquiry</h4>
<h3>Stay connected with us</h3>
<form ref={form} onSubmit={sendEmail}>
<div>
<input type="text" id="name" required placeholder='Your full name' name="user_name" />
</div>
<div>
<input type="email" id="email" required placeholder='Your email address' name="user_email" /></div>
<div>
<textarea id="message" required placeholder='Your message' name="message" />
</div>
<button type="submit" value="Send">Send</button>
</form>
</div>
Hope it would be helpful if you only want to get info from user.

Related

Inability to input text in my forms input boxes in react.js

I am unable to type within my label boxes, this has got me incredibly confused as I'm trying to make a simple username/password registration form that logs the data into a database, however this isn't really possible without having the ability to input data. Wondering if I can get some assistance.
import axios from "axios";
import React, { useState } from "react";
export default function Home() {
const [user, setUser] = useState({
username: "",
password: "",
});
const { username, password} = user;
const onInputChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value });
};
const onSubmit = async (e) => {
e.preventDefault();
await axios.post("http://localhost:8080/user", user);
};
return (
<div className="container">
<div className="row">
<div className="col-md-6 offset-md-3 border rounded p-4 mt-2 shadow">
<h2 className="text-center m-4">Register User</h2>
<form onSubmit={(e) => onSubmit(e)}>
<div className="mb-3">
<label htmlFor="Username" className="form-label">
Username
</label>
<input
type={"text"}
className="form-control"
placeholder="Enter your username"
name="Username"
value={username}
onChange={(e) => onInputChange(e)}
/>
</div>
<div className="mb-3">
<label htmlFor="Password" className="form-label">
Password
</label>
<input
type={"text"}
className="form-control"
placeholder="Enter your Password"
name="Password"
value={password}
onChange={(e) => onInputChange(e)}
/>
</div>
<button type="submit" className="btn btn-outline-primary">
Submit
</button>
</form>
</div>
</div>
</div>
);
}
I looked at the code but i’m just incredibly confused, it looks fine to me
This is because you don't have the correct names in your input.
Replace Password by password and Username by username.
It has to be the same as in your state.

Error When sending an email using the EmailJS with react hook form

I built a form using "react-hook-form", and now at the moment of the submit I want to send a email using mailjs, but it is returning me these errors:
sendPost.js:22 POST https://api.emailjs.com/api/v1.0/email/send-form 422 (Unprocessable Entity)
The recipient address is empty
Here's my function to send the email:
const sendEmail = (e) => {
emailjs.sendForm('ServiceID', 'TemplateID', form.current, 'USERID')
.then((result) => {
console.log(result.text);
alert("Sucess!")
navigate('/results')
}, (error) => {
console.log(error.text);
});
};
And here is my form:
return(
<div className='box'>
<div className='login-section'></div>
<div className='login-text'>Thanks for answering the quiz, your score is {location.state.score} Please insert your name and email to send the results</div>
<form ref={form} onSubmit={handleSubmit(sendEmail)}>
<label>
Name
<input type='text' name='user_name' {...register("name", { required: true })}/>
<span>{errors.name?.message}</span>
</label>
<label>
Email
<input type='text' name='user_email' {...register("email" , { required: true })}/>
<span>{errors.email?.message}</span>
</label>
<input type='hidden' name='score' value={location.state.score}/>
<button type='submit'>Send</button>
</form>
</div>
)
Not sure what's happening here, for me it seems all correct, any clues?
Looks like onSubmit={sendEmail} should do the work for you.

Client leaves channel when sending message in agora Web RTC

I am using Agora Web RTC SDK to create a messaging app, but when a client sends a message after successfully logging in and connecting to the channel, it leaves the channel on its own. I have also used event.preventDefault(), still the page reloads and the client leaves the channel.
Following is my code.
import AgoraRTM from 'agora-rtm-sdk';
import { useState } from 'react';
function Chat(){
const [messageContent,setMessageContent]=useState("");
const [channelName,setChannelName]=useState("");
const [channel,setChannel]=useState();
const [token,setToken]=useState();
const [uid,setUid]=useState();
const [userInChannel,setUserInChannel]=useState(false);
const client = AgoraRTM.createInstance("Actual appID", { enableLogUpload: false });
async function handleLogin(event){
await client.login({uid,token})
console.log(client);
setChannel(client.createChannel(channelName));
event.preventDefault();
}
async function handleJoin(){
await channel.join();
setUserInChannel(true);
}
async function handleSend(event){
await channel.sendMessage({text:messageContent})
event.preventDefault();
}
{userInChannel && channel.on('ChannelMessage',({message,memberID})=>{
console.log("channel Message:" ,message);
console.log("member ID:",memberID);
})}
return(
<div>
<form onSubmit={handleJoin}>
<input type='text' name='token' onChange={(event) => { setToken(event.target.value) }} placeholder="Token" />
<input type='text' name='channel' onChange={(event) => { setChannelName(event.target.value) }} placeholder="Channel Name" />
<input type='text' name='uid' onChange={(event) => { setUid(event.target.value) }} placeholder="Enter Uid" />
<div className='button-group'>
<button id='join' type='button' className='btn btn-primary btn-sm' onClick={handleLogin}>Login</button>
<button id='join' type='button' className='btn btn-primary btn-sm' onClick={handleJoin}>Join Channel</button>
</div>
</form>
<form onSubmit={handleSend}>
<input type="text" name="message" value={messageContent} placeholder='Enter your message...' onChange={(event)=>{setMessageContent(event.target.value)}} />
<button>Send</button>
</form>
</div>
)
}
export default Chat;

How to send form data to email in React JS?

I have to send form datas to an email address.
How can I do?
I did some research and I understand that you have to use a library to do this. correct?
What do you suggest?
I think this one might be worth looking into - https://www.emailjs.com/docs/sdk/send-form/
If you are looking for implementation for Reactjs then use like this :
// install #emailjs/browser
import React, { useRef } from 'react';
import emailjs from '#emailjs/browser';
export const ContactUs = () => {
const form = useRef();
const sendEmail = (e) => {
e.preventDefault();
// service_id, templte_id and public key will get from Emailjs website when you create account and add template service and email service
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>
);
};

Netify-gatsby form submission not working with custom Success Component

I am using Netify-form with gatsby JS. I am trying to show a success alert Component when a user submits the form. This is working fine, but I am not able to get form data under my Netify account.
handleSubmit = (e) => {
this.setState({showSuccessMsg: true});
e.preventDefault();
};
<form name="subscribe"
method="POST"
onSubmit={this.handleSubmit} // custom handler
action=""
data-netlify="true"
data-netlify-honeypot="bot-field"
className="form-inline d-flex">
<input type="hidden" name="form-name" value="subscribe"/>
<input type="hidden" name="bot-field"/>
.....
.....
<button type="submit" className="btn btn-primary mx-auto">
Subscribe
</button>
</form>
<div>
{this.state.showSuccessMsg ? <SuccessAlert/> : ''}
</div>
PS: commenting this // onSubmit={this.handleSubmit}, I am able to get data but I am loosing showing success alert.
Netlify forms setup - Success messages
By default, when visitors complete a form, they will see a generically styled success message with a link back to the form page. You can replace the default success message with a custom page you create by adding an action attribute to the tag, entering the path of your custom page (like "/pages/success") as the value. The path must be relative to the site root, starting with a /.
Or you could check out this guide from Netlify - How to Integrate Netlify’s Form Handling in a React App which has a gatsby specific example for submitting with js.
import React, {useState} from 'react'
function encode(data) {
return Object.keys(data)
.map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
.join('&')
}
export default function Contact() {
const [state, setState] = useState({})
const handleChange = (e) => {
setState({ ...state, [e.target.name]: e.target.value })
}
const handleSubmit = (e) => {
e.preventDefault()
const form = e.target
fetch('/', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: encode({
'form-name': form.getAttribute('name'),
...state,
}),
})
.then(() => alert('success')))
.catch((error) => alert(error))
}
return (
<>
<h1>Contact</h1>
<form
name="contact"
method="post"
action="/thanks/"
data-netlify="true"
data-netlify-honeypot="bot-field"
onSubmit={handleSubmit}
>
{/* The `form-name` hidden field is required to support form submissions without JavaScript */}
<input type="hidden" name="form-name" value="contact" />
<div hidden>
<label>
Don’t fill this out: <input name="bot-field" onChange={handleChange} />
</label>
</div>
<label>
Your name:
<input type="text" name="name" onChange={handleChange} />
</label>
<label>
Your email:
<input type="email" name="email" onChange={handleChange} />
</label>
<label>
Message:
<textarea name="message" onChange={handleChange} />
</label>
<button type="submit">Send</button>
</form>
</>
)
}

Resources