#Handling form data inside Astro Page using React
4 messages · Page 1 of 1 (latest)
Hi @modest harness. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To handle form data inside an Astro page using React, you can follow these steps:
- Create a form using React: You can create a form using React and include a
nameattribute for each input field that describes the value of that input. Be sure to include a<button>or<input type="submit">element to submit the form. Here's an example:
export default function Form() {
return (
<form>
<label> Name <input type="text" id="name" name="name" required /> </label>
<label> Email <input type="email" id="email" name="email" required /> </label>
<label> Message <textarea id="message" name="message" required /> </label>
<button>Send</button>
</form>
);
}
(Source: Astro Documentation (https://docs.astro.build/en/recipes/build-forms-api#recipe))
- Create a POST API endpoint: You need to create a
POSTAPI endpoint that will receive the form data. Userequest.formData()to process it. Be sure to validate the form values before you use them. Here's an example:
import type { APIRoute } from "astro";
export const POST: APIRoute = async ({ request }) => {
const data = await request.formData();
const name = data.get("name");
const email = data.get("email");
const message = data.get("message");
// Validate the data
if (!name || !email || !message) {
return new Response(
JSON.stringify({ message: "Missing required fields", }),
{ status: 400 }
);
}
// Do something with the data, then return a success response
return new Response(
JSON.stringify({ message: "Success!" }),
{ status: 200 }
);
};
(Source: Astro Documentation (https://docs.astro.build/en/recipes/build-forms-api#recipe))
- Handle form submission: The form submission will cause the browser to request the page again. Change the form’s data transfer
methodtoPOSTto send the form data as part of theRequestbody, rather than as URL parameters. Check for thePOSTmethod in the frontmatter and access the form data usingAstro.request.formData(). Wrap this in atry ... catchblock to handle cases when thePOSTrequest wasn’t sent by a form and theformDatais invalid. Here's an example:
---if (Astro.request.method === "POST") {
try {
const data = await Astro.request.formData();
const name = data.get("username");
const email = data.get("email");
const password = data.get("password");
// Do something with the data
} catch (error) {
if (error instanceof Error) {
console.error(error.message);
}
}
}---
(Source: Astro Documentation (https://docs.astro.build/en/recipes/build-forms#recipe))
- Validate the form data on the server: This should include the same validation done on the client to prevent malicious submissions to your endpoint and to support the rare legacy browser that doesn’t have form validation.