I think I’ve found a solution. I’ve created a fake form outside the Formik
's form element, with all the necessary Netlify attributes (right form name, data-netlify) in order to let Netlify pick the right markup
<form
hidden
name="contact-us"
data-netlify="true"
netlify-honeypot="bot-field"
>
<input type="text" name="name" />
<input type="text" name="email" />
<input type="textarea" name="message" />
</form>
and then I send the values form my formik form via the handleSubit
method from formik / post request.
const createFormDataObj = data => {
const formData = new FormData();
Object.keys(data).forEach(k => {
formData.append(k, data[k]);
});
return formData;
};
const handleSubmit = formValues => {
const { name, email, message } = formValues;
const data = {
'form-name': 'contact-us',
name: name,
email: email,
message: message,
};
fetch('/', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams(createFormDataObj(data)).toString(),
})
.then(() => setMessage('Thank you, your request has been sent'))
.catch(error => {
console.log(error);
setMessage('There was an error sending your request, try again later');
});
};