HI all,
I want to set up my form component to send emails to my email account when a form is submitted.
To do this, I created a custom code component as a test, which works fine.
export function ContactForm({ className }: { className?: string }) {
const submitForm = async (event: any) => {
event.preventDefault();
const formData = new FormData(event.target);
console.log(JSON.stringify(Object.fromEntries(formData)))
formData.append('access_key', 'MY_API_KEY');
const res = await fetch('https://api.web3forms.com/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(Object.fromEntries(formData))
}).then(res => res.json());
if(res.success) {
console.log('success')
}
}
return (
<form className={className} onSubmit={submitForm}>
<div className="input-box">
<input type="text" placeholder="Full Name*" name="name" required/>
<input type="text" placeholder="Subject*" name="subject" required/>
<input type="text" placeholder="Your email*" name="email" required/>
<input type="text" placeholder="Write your message*" name="message" required/>
<button type="submit">Send</button>
</div>
</form>
)
}
However, I would like to use the built-in form component instead for a couple of reasons:
- Gives me better flexibility in terms of styling; turning off simple form mode would enable me to use style presets
- Would like to use native features as much as possible to reduce workload
My current approach is to integrate an HTTP request when the submit button is clicked, but I am not able to access the formData object from the native form component (or at least can’t figure out how to access it)
Can someone kindly point out how I can set up my API integration?
Any pointers would be much appreciated if there is a better way to approach this problem.
Thank you!