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 interact
4 min read
How to Load Data from a File in Next.js?
Loading Data from files consists of using client-side techniques to read and process files in a Next.js application. In this article, we will explore a practical demonstration of Load Data from a File in Next.js. We will load a validated CSV input file and display its contents in tabular format. App
3 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 mi
2 min read
How to add Calendar in Next.js ?
Adding a calendar to a Next.js application enhances scheduling and event management. We can just install and use the available npm package. In this article, we are going to learn how we can add a calendar loader in NextJS. ApproachTo add our calendar we are going to use the react-calendar package. T
2 min read
How to create a Custom Error Page in Next.js ?
Creating a custom error page in Next.js allows you to provide a better user experience by customizing the appearance and messaging of error pages like 404 and 500. In this post we are going to create a custom error page or a custom 404 page in a Next JS website. What is a custom error page?The 404 p
2 min read
Create a Form using React JS
Creating a From in React includes the use of JSX elements to build interactive interfaces for user inputs. We will be using HTML elements to create different input fields and functional component with useState to manage states and handle inputs. Prerequisites:Functional ComponentsJavaScript ES6JSXPr
5 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,
3 min read
How are forms created in ReactJS ?
Form is a document that stores information of a user on a web server using interactive controls. A form contains different kinds of information such as username, password, contact number, email ID, etc. Creating a form in React is almost similar to that of HTML if we keep it simple and just make a s
3 min read