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

bookWorking with Forms in Next.js

Scorri per mostrare il menu

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?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 26

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 1. Capitolo 26
some-alt