How to handle form submissions in Next.js



Image not found!!

Handling form submissions in Next.js involves a combination of using the built-in next/router for client-side navigation and handling form data on the server side. Here's a step-by-step guide:

Client-Side Handling:

  1. Create a Form Component: Create a React component for your form. For example, components/MyForm.js:

    jsx
    import { useState } from 'react'; const MyForm = () => { const [formData, setFormData] = useState({}); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); }; const handleSubmit = (e) => { e.preventDefault(); // Handle form submission here, e.g., send data to the server console.log('Form submitted with data:', formData); // You can use fetch or any library to send data to the server }; return ( <form onSubmit={handleSubmit}> <label> Name: <input type="text" name="name" onChange={handleChange} /> </label> <br /> <label> Email: <input type="email" name="email" onChange={handleChange} /> </label> <br /> <button type="submit">Submit</button> </form> ); }; export default MyForm;
  2. Integrate the Form Component: Integrate your form component in a page:

    jsx
    import MyForm from '../components/MyForm'; const MyPage = () => { return ( <div> <h1>My Page</h1> <MyForm /> </div> ); }; export default MyPage;

Server-Side Handling:

  1. Create an API Route: Create an API route to handle form submissions. For example, in the pages/api directory, create a file submitForm.js:

    jsx
    export default function handler(req, res) { if (req.method === 'POST') { // Handle the form submission on the server const { name, email } = req.body; console.log('Form submitted with data:', { name, email }); // Process the data, store in a database, etc. // Send a response res.status(200).json({ message: 'Form submitted successfully' }); } else { res.status(405).json({ message: 'Method Not Allowed' }); } }
  2. Update Form Submission in Component: Update the form submission logic in your component to use the API route:

    jsx
    import { useState } from 'react'; const MyForm = () => { const [formData, setFormData] = useState({}); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); }; const handleSubmit = async (e) => { e.preventDefault(); // Send data to the server const response = await fetch('/api/submitForm', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(formData), }); if (response.ok) { console.log('Form submitted successfully'); // You can handle success here, e.g., redirect the user } else { console.error('Form submission failed'); // Handle the error } }; return ( <form onSubmit={handleSubmit}> {/* ... (same as before) */} </form> ); }; export default MyForm;

Now, when the form is submitted, the data is sent to the server-side API route for further processing, and you can handle the success or error accordingly. The fetch API is used here for simplicity, but you might want to use a library like Axios for more advanced features.