0
0
NextjsDebug / FixBeginner · 4 min read

How to Handle Form in Next.js: Simple and Correct Approach

In Next.js, handle forms by using React's useState to track input values and onSubmit event to process the form. Prevent the default form submission with event.preventDefault() to control behavior and update state as users type.
🔍

Why This Happens

When handling forms in Next.js, a common mistake is not preventing the default form submission, which causes the page to reload and lose input data. Also, not using React state to track input values means the form cannot update or display user input properly.

javascript
import React from 'react';

export default function ContactForm() {
  return (
    <form>
      <input type="text" name="name" />
      <button type="submit">Submit</button>
    </form>
  );
}
Output
Page reloads on submit and input data is lost.
🔧

The Fix

Use React's useState to store input values and add an onSubmit handler that calls event.preventDefault() to stop page reload. Update state on input changes to keep form data in sync.

javascript
import React, { useState } from 'react';

export default function ContactForm() {
  const [name, setName] = useState('');

  function handleSubmit(event) {
    event.preventDefault();
    alert(`Form submitted with name: ${name}`);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">Name:</label>
      <input
        id="name"
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        required
      />
      <button type="submit">Submit</button>
    </form>
  );
}
Output
Form submits without page reload and shows alert with entered name.
🛡️

Prevention

Always use React state to control form inputs and prevent default form submission to avoid page reloads. Use controlled components by setting value and onChange. Validate inputs before submission and keep handlers simple.

Use linting tools like ESLint with React plugin to catch missing event.preventDefault() or uncontrolled inputs.

⚠️

Related Errors

Uncontrolled to Controlled Input Warning: Happens when input switches from uncontrolled (no value) to controlled (with value). Fix by always setting value and onChange.

Form Submission Reloads Page: Fix by adding event.preventDefault() in submit handler.

Key Takeaways

Use React's useState to track form input values as controlled components.
Always call event.preventDefault() in form submit handlers to stop page reload.
Update state on input changes to keep form data in sync with user input.
Validate inputs and keep form handlers simple and clear.
Use linting tools to catch common form handling mistakes early.