How to send form data to email in React JS? - reactjs

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>
);
};

Related

Sending email in react js

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.

How to set up Rails active storage on the front end React form?

Im stuck in the part where in I can set up my front end for Image uploads.I have set up my backend correctly for uploading images via active storage.Following this article "https://medium.com/#aliceshulin66/active-storage-in-react-rails-fb24c73227ff".However im conused about the front end.I need to add image upload to the review component. heres my code
import { useState } from "react";
import { useParams } from "react-router-dom";
import { useContext } from "react";
import { Cont } from "../Cont";
// handleAddReviews={(review) => setReviews([...reviews, review])}
function AddReviewForm({handleAddReviews}){
const {user}=useContext(Cont);
const params = useParams();
const[img,setImg]=useState("");
const[r,setR]=useState("");
const [images, setImages]=useState([])
function handleReviewSubmit(event) {
event.preventDefault();
const formData=new formData()
formData.append('r',r)
for (let i=0;i<images.length;i++){
formData.append('images[]',images[i])
}
formData.append("user_id",parseInt(user))
formData.append("restaurant_id",params.id)
fetch(`/reviews`, {
method:"POST",
body:formData
})
.then((r) => r.json())
.then(()=>{
window.location.reload()
}
);
}
return (
<>
<h1>Add review form</h1>
<form onSubmit={handleReviewSubmit}>
<div>
<input type="file" accept="image/*" multiple onChange={e=>setImages(newImage=> ({...newImage, images: e.target.files}))}/>
{/* <input
required
type="file"
name="picture"
accept="image/png, image/gif, image/jpeg"
id="picture"
// onChange={e => {setNewTrash(newTrash => ({...newTrash, picture: e.target.files[0]}))}}
/> */}
</div>
<div>
<label htmlFor="r" >Review</label>
<input type="text" name="r" value={r} onChange={(e) => setR(e.target.value)} placeholder="review" />
</div>
<input type="submit" />
</form>
</>
)
}
export default AddReviewForm;

Get id from one form out of multiple forms? (React)

I am trying send only one of my form's id to my handleSubmit function in react. My forms are created via a map function, which creates a form for each data enter from my DB. My handleSubmit function currently take in an event and outputs it to the console log. When running the code, I get all of my id's instead of one. Any help?
Here is my code:
import React, { useRef, useState } from 'react';
export const Movie = ({listOfReviews}) =>{
const handleSubmit = (event) => {
console.log(event)
}
return (
<>
<h1>Your reviews:</h1>
{listOfReviews.map(review =>{
return(
<form onSubmit={handleSubmit(review.id)}>
<label>
Movieid:{review.movieid}
<input type="text" value={review.id} readonly="readonly" ></input>
<input type="text" value={review.comment}></input>
<input type="submit" value="Delete"></input>
</label>
</form>
)
})}
</>
)
}
You have a simple error in your onSubmit callback. Instead of calling handleSubmit in the callback prop, you should instead define an inline function that calls handleSubmit.
Like this:
<form onSubmit={() => handleSubmit(review.id)}>
Full code:
import React, { useRef, useState } from 'react';
export const Movie = ({ listOfReviews }) => {
const handleSubmit = (id) => {
console.log(id);
};
return (
<>
<h1>Your reviews:</h1>
{listOfReviews.map((review) => {
return (
<form onSubmit={() => handleSubmit(review.id)}>
<label>
Movieid:{review.movieid}
<input type="text" value={review.id} readonly="readonly"></input>
<input type="text" value={review.comment}></input>
<input type="submit" value="Delete"></input>
</label>
</form>
);
})}
</>
);
};

How can I reset the form values in a React component with a button press?

I'm using the below Contact component to handle a simple form in react to send an email. I want the sendEmail function to also clear the form fields but I've tried referencing them through form.current and that doesnt seem to be working. Is there another way I need to reference them to set the values? I also tried e.target.reset() and it didn't seem to do anything.
import React, { useRef } from 'react';
import emailjs from 'emailjs-com';
const Contact = () => {
const form = useRef();
const sendEmail = (e) => {
e.preventDefault();
const serviceId='...';
const templateId='...';
const userId='...';
emailjs.sendForm(serviceId, templateId, form.current, userId)
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
};
return (
<form onSubmit={sendEmail} ref={form}>
<div className="field half first">
<label htmlFor="name">Name</label>
<input type="text" name="fromName" id="name"/>
</div>
<div className="field half">
<label htmlFor="email">Email</label>
<input type="text" name="fromEmail" id="email"/>
</div>
<div className="field">
<label htmlFor="message">Message</label>
<textarea name="message" id="message" rows="4"
placeholder = "..."></textarea>
</div>
<ul className="actions">
<li>
<input type="submit" value="Send Message" className="special"/>
</li>
</ul>
</form>
);
};
export default Contact
There are so many ways to doing this, basically on how the component has been structured to collect the data. However, following your pattern of arrangement, why don't you set a boolean variable or something coercible to a boolean value (value initially set to false) that is made aware (i.e value changes to true or 'sent') when the email has been successfully sent.
import {useState} from "react";
const [emailStatus, setEmailStatus] = useState("Not sent");
Then use the useEffect-hook to re-render the component, whenever the emailStatus variable changes to true or 'sent' and thereby clear-out the form values.
Hence, in your function:
emailjs.sendForm(serviceId, templateId, form.current, userId)
.then((result) => {
.... any other logic
console.log(result.text);
setEmailStatus('sent');
................
useEffect(() => {
//clear form fields here
}, [emailStatus]);
return(
.....
.....
);

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