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

bookWorking with Forms in Next.js

Svep för att visa menyn

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?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 26

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 1. Kapitel 26
some-alt