Reputation: 31
I am building a contact form with React and formik. I want to use Email.Js which will allow me to send an email/details of my contact form via email super easily. However, there aren't really any documents that pertain to integrating formik and EmailJs.If anyone has used such technologies together it would be cool if you could offer any advice. Here is my code and this is what I am trying to do. I am still somewhat new to React so let me know if I am doings something wrong...
This is the non formik way to do things. Just pass onSubmit and call the function.
<form className="contact-form" onSubmit={sendEmail}>
Here is my code that pertains to my formik form, and then my onSubmit formkik attribute. I don't know exactly where I need to pass the sendEmail() function. I can't get this working and I have been getting various errors/warnings such as "An unhandled error was caught from submitForm() Expected the HTML form element or the style selector of form"
<div className="buy-form-cont">
<Formik
initialValues={{
name: "",
email: "",
powerWashed: false,
options: "",
info: "",
}}
validationSchema={validationSchema}
onSubmit={(values, { setSubmitting, resetForm,}) => {
sendEmail(values)
console.log("submit", values);
alert(
"Thank you for the submission. Korionna will be in contact with you shortly"
);
setSubmitting(false);
resetForm();
}}
>
Upvotes: 1
Views: 1755
Reputation: 31
You have 2 options to send emails using emailjs:
Here's an example:
import {Formik, Field, Form} from 'formik';
import emailjs, {send} from 'emailjs-com'
export default function ContactForms() {
function SendEmail(object) {
emailjs.send("serviceID", "templadeID", object,"userID" )
.then((result) => {
console.log(result.text)
}, (error) => {
console.log(error.text)
})
}
return (
<Formik
initialValues={{ name: "" }}
onSubmit={(values, actions) => {
setTimeout(() => {
SendEmail(values)
actions.setSubmitting(false)
}, 1000)
}}
>
{(props) => (
<Form>
<Grid templateColumns="repeat(2, 1fr)" gap="4">
<Field name="name" validate={validateName}>
{({ field, form }) => (
<Box>
<FormControl isInvalid={form.errors.name && form.touched.name}>
<FormLabel htmlFor="name">First name</FormLabel>
<Input {...field} id="name" placeholder="name" />
<FormErrorMessage>{form.errors.name}</FormErrorMessage>
</FormControl>
</Box>
)}
</Field>
<Button
mt={4}
colorScheme="teal"
isLoading={props.isSubmitting}
type="submit"
>
Submit
</Button>
</Form>
)}
</Formik>
)
}
Ignore the styles :P
If you want to send with formik, formik returns you an object which you're required to use the emailjs.send()
which it accepts objects. If you use emailjs.sendForm()
it requires you to use event.target
of your html form.
This is what I can guess since you're not showing how are you importing emailjs
nor showing which function are you using and how.
Cheers
Upvotes: 3