Skip to content

Instantly share code, notes, and snippets.

@blivesta
Last active February 18, 2024 23:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save blivesta/01b9585707bbc7828b00a03828a77981 to your computer and use it in GitHub Desktop.
Save blivesta/01b9585707bbc7828b00a03828a77981 to your computer and use it in GitHub Desktop.
Use contact-form-7 API with React
import * as React from 'react';
import * as Yup from 'yup';
import axios from 'axios';
import { Formik } from 'formik';
const URL = process.env.WP_REST_API_BASE_URL;
const USER = process.env.WP_USER;
const PASSWORD = process.env.WP_APPLICATION_PASSWORD;
const TOKEN = typeof window !== 'undefined' && window.btoa(`${USER}:${PASSWORD}`); // Convert Base64
const CF7_ID = process.env.WP_CF7_ID;
const formSchema = Yup.object().shape({
formName: Yup.string().required('Required'),
formEmail: Yup.string()
.email('Invalid email')
.required('Required'),
});
function convertJsontoUrlencoded(obj: any) {
let str = [];
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
str.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
}
return str.join('&');
}
const WpContactForm7 = () => {
const [state, setState] = React.useState(null || '');
return (
<>
<Formik
initialValues={{
formSubject: '',
formName: '',
formEmail: '',
formMessage: '',
}}
validationSchema={formSchema}
onSubmit={(values, { setSubmitting }) => {
const submitData = async () => {
try {
const result = await axios({
url: `${URL}/contact-form-7/v1/contact-forms/${CF7_ID}/feedback`,
headers: {
Authorization: `Basic ${TOKEN}`,
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
},
method: 'POST',
data: convertJsontoUrlencoded(values),
});
setState(result.data.message);
setSubmitting(false);
} catch (error) {
setState('送信に失敗しました。再度お試しください。');
}
};
submitData();
}}
>
{({ values, errors, touched, handleChange, handleBlur, handleSubmit, isSubmitting }) => (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="">
Subject
<input
type="text"
name="formSubject"
onChange={handleChange}
onBlur={handleBlur}
value={values.formSubject}
/>
{errors.formSubject && touched.formSubject ? <div>{errors.formSubject}</div> : null}
</label>
</div>
<div>
<label htmlFor="">
Name *
<input
type="text"
name="formName"
onChange={handleChange}
onBlur={handleBlur}
value={values.formName}
/>
{errors.formName && touched.formName ? <div>{errors.formName}</div> : null}
</label>
</div>
<div>
<label htmlFor="">
Email *
<input
type="email"
name="formEmail"
onChange={handleChange}
onBlur={handleBlur}
value={values.formEmail}
/>
{errors.formEmail && touched.formEmail ? <div>{errors.formEmail}</div> : null}
</label>
</div>
<div>
<label htmlFor="">
Message
<input
type="text"
name="formMessage"
onChange={handleChange}
onBlur={handleBlur}
value={values.formMessage}
/>
{errors.formMessage && touched.formMessage ? <div>{errors.formMessage}</div> : null}
</label>
</div>
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</form>
)}
</Formik>
{state ? <p>{state}</p> : null}
</>
);
};
export default WpContactForm7;
@salmanamemon
Copy link

salmanamemon commented Oct 24, 2021

Hi Blivesta,
This is exactly what i was looking for, Thank you so much.
I am using exactly the same code but it gives this error
{"contact_form_id":4103,"status":"validation_failed","message":"One or more fields have an error. Please check and try again.","invalid_fields":[{"into":"span.wpcf7-form-control-wrap.formName","message":"The field is required.","idref":null,"error_id":"-ve-formName"},{"into":"span.wpcf7-form-control-wrap.formEmail","message":"The field is required.","idref":null,"error_id":"-ve-formEmail"},{"into":"span.wpcf7-form-control-wrap.formSubject","message":"The field is required.","idref":null,"error_id":"-ve-formSubject"},{"into":"span.wpcf7-form-control-wrap.formMessage","message":"The field is required.","idref":null,"error_id":"-ve-formMessage"}],"posted_data_hash":"","into":"#"}

Can you have any solution to it?

Thank you in advance.

@sublimit14
Copy link

Привет Бливеста, это именно то, что я искал, большое спасибо. Я использую точно такой же код, но он дает эту ошибку {"contact_form_id":4103,"status":"validation_failed","message":"One or more fields have an error. Please check and try again.","invalid_fields":[{"into":"span.wpcf7-form-control-wrap.formName","message":"The field is required.","idref":null,"error_id":"-ve-formName"},{"into":"span.wpcf7-form-control-wrap.formEmail","message":"The field is required.","idref":null,"error_id":"-ve-formEmail"},{"into":"span.wpcf7-form-control-wrap.formSubject","message":"The field is required.","idref":null,"error_id":"-ve-formSubject"},{"into":"span.wpcf7-form-control-wrap.formMessage","message":"The field is required.","idref":null,"error_id":"-ve-formMessage"}],"posted_data_hash":"","into":"#"}

У вас есть какое-нибудь решение?

Заранее спасибо.

Hello, were you able to find a solution to your problem? Please share how you were able to get rid of the validation error problem

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment