Yes, it's perfectly fine to have your form in React while using an Astro API. Astro's React integration (https://docs.astro.build/en/guides/integrations-guide/react/) provides support for using React components inside Astro components, including forms.
To call the API from your React form, you can use the fetch function in JavaScript. Here's a basic example:
const handleSubmit = async (event) => {
event.preventDefault();
const data = new FormData(event.target);
const response = await fetch('/api/waitlist', {
method: 'POST',
body: data,
});
if (!response.ok) {
console.error('There was an error!', response.statusText);
} else {
const responseData = await response.json();
console.log('Form data submitted successfully!', responseData);
}
};
<form onSubmit={handleSubmit}>
{/* Your form fields here */}
<button type="submit">Submit</button>
</form>
In this example, handleSubmit is an async function that gets called when the form is submitted. It prevents the default form submission, creates a FormData object from the form, and sends a POST request to the /api/waitlist endpoint with the form data.
If the request is successful, it logs the response data. If not, it logs an error message. You can replace these console logs with your own error handling and success handling logic.
Remember to replace 'api/waitlist' with your actual API endpoint. Also, ensure that your server-side code is set up to handle POST requests and parse form data.