Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Working with Forms in Next.js | Section
Building Web Apps with Next.js

bookWorking with Forms in Next.js

Veeg om het menu te tonen

Forms are used to collect user input, such as contact messages, login data, or search queries. In Next.js, forms are built using standard HTML elements and enhanced with React for handling user interaction.

To make a form interactive, it should be implemented inside a Client Component, because forms rely on user input and event handling.

Example - Basic Form

"use client";

import { useState } from "react";

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

  return (
    <form>
      <input
        type="text"
        placeholder="Enter your name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <button type="submit">Submit</button>
    </form>
  );
}

This form captures user input using state.

Handling Form Input

When a user types into an input field, the value is stored in component state. This allows you to control and use the input data.

You can manage multiple fields by adding more state variables or using a single object to store all form data.

Preventing Default Behavior

By default, forms reload the page when submitted. In most cases, you want to prevent this behavior and handle submission manually.

"use client";

import { useState } from "react";

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

  function handleSubmit(e) {
    e.preventDefault();
    console.log(name);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <button type="submit">Submit</button>
    </form>
  );
}

Why Forms Are Important

Forms allow users to interact with your application by sending data. They are essential for features like authentication, messaging, and data submission.

In Next.js, forms are typically connected to backend logic using route handlers, which you will learn next.

question mark

Why are forms usually implemented as Client Components in Next.js?

Selecteer het correcte antwoord

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 1. Hoofdstuk 26

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 1. Hoofdstuk 26
some-alt