How to Create a Next.js form ?
Last Updated :
13 May, 2024
Forms are an essential part of many web applications, allowing users to input data and interact with the website. Next.js, with its powerful features for building server-rendered React applications, provides an ideal platform for creating forms. In this article, we'll explore step-by-step how to create a form in Next.js, covering everything from basic setup to form submission handling.
Output Preview:
final formPrerequisites:
Approach to create a NextJS form
- Begin by setting up a Next.js project using the appropriate command (e.g.,
npx create-next-app
) to initialize the project structure and dependencies. - Create a
<form>
element and include input fields for text, textarea, number, radio, checkbox, and select-options, each with a corresponding label. - Add input elements like text, textarea, number, radio buttons, checkboxes, and select-options for user input.
- Incorporate buttons for form submission and resetting.
- Define CSS classes in a module file (e.g., Form.module.css) to style form elements.
- Manage form data using
useState
hook to update state variables dynamically. - Implement
onChange
event handlers to capture user input and update state variables. Ensure data validation for a seamless user experience.
Steps to Setup NextJS Application
Step 1: Create a NextJS application by using this command
npx create-next-app demonext
Step 2: Navigate to project directory
cd demonext
Project Structure:

The updated dependencies in package.json file will look like:
"dependencies": {
"next": "12.1.0",
"react": "^17.0.2",
"react-dom": "^17.0.2"
}
Example: Implementation to create a form in NextJS.
CSS
/* form.module.css */
.form {
max-width: 400px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
.label {
display: block;
margin-bottom: 5px;
}
.input,
.radio,
.select,
.button {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
.input[type="number"] {
width: 100%;
}
.radio {
margin-right: 10px;
}
.button {
background-color: #1c5f3a;
color: #fff;
cursor: pointer;
}
.button:hover {
background-color: #124127;
}
JavaScript
// components/Form.js
import React, { useState } from "react";
import styles from "./Form.module.css"; // Updated import path
const Form = () => {
const [formData, setFormData] = useState({
firstName: "",
lastName: "",
email: "",
address: "",
age: "",
gender: "",
interests: [],
});
const handleChange = (e) => {
const { name, value, type, checked, options } = e.target;
if (type === "checkbox") {
const selectedOptions = Array.from(options)
.filter((option) => option.selected)
.map((option) => option.value);
setFormData({ ...formData, [name]: selectedOptions });
} else if (type === "radio" && checked) {
setFormData({ ...formData, [name]: value });
} else {
setFormData({ ...formData, [name]: value });
}
};
const handleSubmit = (e) => {
e.preventDefault();
console.log("Form Data:", formData);
};
return (
<form className={styles.form} onSubmit={handleSubmit}>
<label htmlFor="firstName" className={styles.label}>
First Name:
</label>
<input
type="text"
id="firstName"
name="firstName"
value={formData.firstName}
onChange={handleChange}
className={styles.input} />
<label htmlFor="lastName" className={styles.label}>
Last Name:
</label>
<input
type="text"
id="lastName"
name="lastName"
value={formData.lastName}
onChange={handleChange}
className={styles.input} />
<label htmlFor="email" className={styles.label}>
Email:
</label>
<input
type="email"
id="email"
name="email"
value={formData.email}
onChange={handleChange}
className={styles.input} />
<label htmlFor="address" className={styles.label}>
Address:
</label>
<textarea
id="address"
name="address"
value={formData.address}
onChange={handleChange}
className={styles.input} />
<label htmlFor="age" className={styles.label}>
Age:
</label>
<input
type="number"
id="age"
name="age"
value={formData.age}
onChange={handleChange}
className={styles.input} />
<label className={styles.label}>Gender:</label>
<span style={{ display: "flex" }}>
<label
style={{ width: "20px" }}
htmlFor="male"
className={styles.label}>
Male
</label>
<input
type="radio"
id="male"
name="gender"
value="male"
checked={formData.gender === "male"}
onChange={handleChange}
className={styles.radio} />
</span>
<span style={{ display: "flex" }}>
<label
style={{ width: "20px" }}
htmlFor="female"
className={styles.label}>
Female
</label>
<input
type="radio"
id="female"
name="gender"
value="female"
checked={formData.gender === "female"}
onChange={handleChange}
className={styles.radio} />
</span>
<label htmlFor="interests" className={styles.label}>
Interests:
</label>
<select
id="interests"
name="interests"
multiple
value={formData.interests}
onChange={handleChange}
className={styles.select}>
<option value="coding">Coding</option>
<option value="reading">Reading</option>
<option value="music">Music</option>
</select>
<button type="submit" className={styles.button}>
Submit
</button>
<button type="reset" className={styles.button}>
Reset
</button>
</form>
);
};
export default Form;
JavaScript
//index.js
import Head from "next/head";
import { useEffect, useState } from "react";
import Form from "./form";
export default function Home() {
return (
<>
<Head>
<title>Create Next App</title>
<meta name="description"
content="Generated by create next app" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<div
style={{
height: "100vh",
}}>
<Form />
</div>
</main>
</>
);
}
Step to Run Application:Â Run the application using the following command from the root directory of the project
npm run dev
Output:Â Your project will be shown in the URL http://localhost:3000/
Conclusion
Building forms in Next.js requires paying close attention to details and following the best ways of doing things to make sure users have a smooth experience. This involves using clear HTML elements like input boxes and buttons, checking data both on the user's side and on the server to make sure it's correct, making sure anyone can use the form easily, making the form look good on different devices, and making sure hackers can't mess with it. By doing these things right, your Next.js forms will work well and users will find them easy to use.
Similar Reads
How to Create a New Next JS 13+ App? Creating a new Next.js 13+ application is a straightforward process that sets up a modern React-based framework with built-in features like server-side rendering, static site generation, and API routes. Next JS streamlines and automates the setup of essential React tooling, handling tasks such as bu
2 min read
How to Create a Pre-Filled forms in Node.js ? Pre-Filled forms are those forms that are already filled with desired data. These are helpful when a user wants to update something like his profile, etc. We just create a folder and add a file, for example, index.js. To run this file you need to run the following command. node index.js Filename: Sa
2 min read
How to Create Todo App using Next.js ? In this article, we will create a to-do application and understand the basics of Next.js. This to-do list can add new tasks we can also delete the tasks by clicking on them.Next.js is a widely recognized React framework that eÂnables server-side rendering and enhanceÂs the developmeÂnt of interacti
4 min read
How to Migrate from Create React App to Next JS ? Migrating from Create React App to Next.js is a structured process that includes setting up a Next.js project, reorganizing your files, updating dependencies, and utilizing Next.js features for better performance and server-side rendering.Prerequisites:NPM & Node.jsReact JSNext JSApproach To mig
2 min read
Next.js Create Next App In Next.js, the create next app command is used to automatically initialize a new NextJS project with the default configuration, providing a streamlined way to build applications efficiently and quickly.System Requirements:Node.js 12.22.0 or laterNPM 6.14.4 or later OR Yarn 1.22.10 or latermacOS, Wi
3 min read
How to add ESLint in Next.js ? ESLint is a popular linting tool for identifying and fixing issues in JavaScript code. Adding ESLint to your Next.js project ensures that your code follows best practices and maintains a consistent style. This enhances code quality, helps catch errors early, and makes the codebase easier to maintain
3 min read
How to add CodeBlock in Next.js ? In this article, we are going to learn how we can add CodeBlock in NextJS. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditiona
2 min read
How to Add Form Validation In Next.js ? Forms play a crucial role in modern web applications by ensuring the accuracy and validity of data. NeÂxt.js, a versatile framework for building ReÂact applications, offers form validation that helps verify useÂr input against predefined criteÂria, provides immediate feedback, and enhances data qual
3 min read
How to Catch All Routes in Next.js ? To catch all routes in Next.js, you create a dynamic route file using the catch-all segments syntax. This allows you to handle various routes dynamically, enhancing routing flexibility and application structure.Catch all routesTo catch all routes in next js, We willCreate a file named [...gfg].js in
2 min read
Create a Quiz App with Next JS In this article, weâll explore the process of building a Quiz App utilizing NextJS. The quiz app provides users with a series of multiple-choice questions with options. Users can select the option and move to the next question. At the end, the user will be able to see the analysis of the quiz.Output
5 min read