Form handling in Next.js – Headless WP + Next.js Blog [part 12]
Form handling in Next.js is an essential part of creating interactive and dynamic websites. In this article, we will cover how to handle forms in a Next.js application that is set up with Headless WordPress.
First, we need to create a form in our Next.js application. We can use HTML form tags to create a basic form like this:
In the above HTML, we have created a basic form with two input fields for name and email. When the form is submitted, it will send a POST request to /submit-form endpoint.
Now, let’s look at how we can handle form submission in our Next.js application. We can use the built-in fetch API to send a POST request to our WordPress backend when the form is submitted. Here’s an example of how we can handle form submission in a Next.js component:
“`javascript
import React, { useState } from ‘react’;
const Form = () => {
const [name, setName] = useState(”);
const [email, setEmail] = useState(”);
const handleSubmit = async (e) => {
e.preventDefault();
const res = await fetch(‘/api/submit-form’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({ name, email }),
});
if (res.ok) {
alert(‘Form submitted successfully’);
} else {
alert(‘Form submission failed’);
}
};
return (
setName(e.target.value)}
/>
setEmail(e.target.value)}
/>
);
};
export default Form;
“`
In the above example, we have created a Form component that uses React state to store the form input values. When the form is submitted, we send a POST request to /api/submit-form endpoint using the fetch API. We then display an alert based on the response from the server.
That’s it! With these steps, you can now handle form submission in your Next.js application that is set up with Headless WordPress. This allows you to create interactive and dynamic forms that interact with your WordPress backend.
I'm working with O2Switch, do you think i can use O2switch and vercel and follow this tutorial ?
sir, can we send this form data to the wordpress backend ?
It's not editable in wordpress dashboard…
🙋♂
Thanks for your tutorial.👍 How can I add a function crud a post ?