Introduction: Forms are a crucial part of web applications, enabling user interaction and data submission. In Next.js, a popular React framework for building web applications, handling forms effectively is essential for creating seamless user experiences.
In this guide, we'll explore the best practices for form handling in Next.js applications, along with practical code examples to illustrate each concept. 1. Use Controlled Components: Controlled components are React components where form data is handled by React instead of the DOM. In Next.js, leveraging controlled components ensures that form inputs are always in sync with the component's state, facilitating easier data management and validation.
Example:
import React, { useState } from 'react';
const MyForm = () => {
const [formData, setFormData] = useState({
username: '',
password: '',
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
// Handle form submission logic here
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
/>
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
Example:
// Inside API route (e.g., pages/api/login.js)
export default function handler(req, res) {
const { username, password } = req.body;
// Perform server-side validation
if (!username || !password) {
return res.status(400).json({ error: 'Username and password are required' });
}
// Proceed with authentication logic
}
Example with Formik:
import { Formik, Form, Field, ErrorMessage } from 'formik';
const MyForm = () => (
<Formik
initialValues={{ username: '', password: '' }}
validate={(values) => {
const errors = {};
if (!values.username) {
errors.username = 'Required';
}
// Add more validation rules as needed
return errors;
}}
onSubmit={(values, { setSubmitting }) => {
// Handle form submission logic
}}
>
{({ isSubmitting }) => (
<Form>
<Field type="text" name="username" />
<ErrorMessage name="username" component="div" />
<Field type="password" name="password" />
<ErrorMessage name="password" component="div" />
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</Form>
)}
</Formik>
);
export default MyForm;
