Using FormBeep in React#
If you are building a React application (e.g., Create React App, Next.js, Remix, Vite), you have two options for integrating FormBeep:
Option 1: Direct API Call (Recommended)#
Because React manages its own state and synthetic events, the cleanest way to use FormBeep is to call our API directly using fetch. You completely bypass the formbeep.js embed script.
import { useState } from 'react';
export default function ContactForm() {
const [status, setStatus] = useState('idle');
async function handleSubmit(e) {
e.preventDefault();
setStatus('submitting');
// Create FormData object from the event target
const formData = new FormData(e.target);
// OPTIONAL: Convert to JSON if you prefer sending application/json
const data = Object.fromEntries(formData.entries());
try {
const response = await fetch('https://api.formbeep.com/v1/submit/YOUR_API_KEY', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(data),
});
if (response.ok) {
setStatus('success');
e.target.reset(); // Clear the form
} else {
setStatus('error');
}
} catch (err) {
console.error(err);
setStatus('error');
}
}
return (
<form onSubmit={handleSubmit}>
<input name="name" placeholder="Name" required />
<input name="email" type="email" placeholder="Email" required />
<textarea name="message" placeholder="Message" required />
<button type="submit" disabled={status === 'submitting'}>
{status === 'submitting' ? 'Sending...' : 'Send'}
</button>
{status === 'success' && <p>Message sent successfully!</p>}
{status === 'error' && <p>Something went wrong. Please try again.</p>}
</form>
);
}Advantages of the API Method:#
- No external
<script>tags to inject into your DOM. - Full control over your component state, loading UI, and error messaging.
Option 2: Script Injection#
If you prefer to let FormBeep handle everything (including honeypot injection and success messages automatically), you can manually append the script to the DOM when your component mounts.
import { useEffect, useRef } from 'react';
export default function FormBeepComponent() {
const formRef = useRef(null);
useEffect(() => {
// Only inject script once
if (!document.getElementById('formbeep-script')) {
const script = document.createElement('script');
script.id = 'formbeep-script';
script.src = 'https://api.formbeep.com/v1/s/formbeep.js';
script.setAttribute('data-api-key', 'YOUR_API_KEY');
script.async = true;
document.body.appendChild(script);
}
}, []);
return (
<form ref={formRef}>
<input name="name" required />
<input name="email" type="email" required />
<textarea name="message" required />
<button type="submit">Submit</button>
</form>
);
}Note: The FormBeep script listens for standard submit events that bubble up to document. Since React uses synthetic events, native bubbling behavior can sometimes be tricky depending on your React version.