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

bookWorking with Forms in Next.js

Sveip for å vise menyen

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?

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 26

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 1. Kapittel 26
some-alt