Next.jsjavascriptfront-end

How To Collect Form Data With NextJS

Picture of the author
Published on
How To Collect Form Data With NextJS

Collecting form data in a Next.js application is essential for many dynamic websites. Whether you're capturing user input or processing data, you can handle form submissions either through built-in HTML behaviors or by leveraging JavaScript. Here's a step-by-step on both approaches:

1. Handling Form Submission with HTML

This method involves creating an HTML form and addressing it server-side or on a different page. Here's the breakdown:

Creating a Form Component

First, create a simple form component:

// components/MyForm.js
import React from 'react';

const MyForm = () => (
  <form action="/api/submit-data" method="post">
    <div>
      <label htmlFor="firstName">First Name:</label>
      <input type="text" id="firstName" name="firstName" required />
    </div>
    <div>
      <label htmlFor="lastName">Last Name:</label>
      <input type="text" id="lastName" name="lastName" required />
    </div>
    <button type="submit">Submit</button>
  </form>
);

export default MyForm;

Setting Up an API Route

Next.js makes it straightforward to handle form submissions with API routes. Create a file to capture and process the form data:

// pages/api/submit-data.js
export default function handler(req, res) {
  if (req.method === 'POST') {
    const { firstName, lastName } = req.body;
    
    // Process the form data here.
    console.log('Received data:', { firstName, lastName });

    res.status(200).json({ message: 'Form data received' });
  } else {
    res.status(405).json({ message: 'Only POST requests allowed' });
  }
}

Updating the Form's Action Attribute

Finally, make sure your form’s action points to the correct API route:

<form action="/api/submit-data" method="post">

2. Handling Form Submission with JavaScript

For more control and flexibility over form submissions, consider using JavaScript to handle the process. This allows for client-side form validation and other dynamic interactions.

Creating a Form Component with JavaScript

Here's an example of a form component that uses JavaScript to handle the submission:

// components/MyForm.js
import React, { useState } from 'react';

const MyForm = () => {
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    const response = await fetch('/api/submit-data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    });

    const result = await response.json();
    console.log(result);
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="firstName">First Name:</label>
        <input
          type="text"
          id="firstName"
          name="firstName"
          value={formData.firstName}
          onChange={handleChange}
          required
        />
      </div>
      <div>
        <label htmlFor="lastName">Last Name:</label>
        <input
          type="text"
          id="lastName"
          name="lastName"
          value={formData.lastName}
          onChange={handleChange}
          required
        />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;

API Route Setup

The API route to handle the form data can reuse the setup from the previous example:

// pages/api/submit-data.js
export default function handler(req, res) {
  if (req.method === 'POST') {
    const { firstName, lastName } = req.body;
    
    // Handle the form data here.
    console.log('Received data:', { firstName, lastName });

    res.status(200).json({ message: 'Form data received' });
  } else {
    res.status(405).json({ message: 'Only POST requests allowed' });
  }
}

Conclusion

Both methods outlined above—direct HTML submission and JavaScript-based submission—offer distinct advantages. The JavaScript approach provides more flexibility for validating and processing data client-side before making a server request. Use the method best suited to your application’s needs to manage form data efficiently in Next.js.

Stay Tuned

Want to become a Next.js pro?
The best articles, links and news related to web development delivered once a week to your inbox.