Working with Forms in Next.js
Stryg for at vise menuen
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.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat