Next.js is a popular JavaScript framework for building modern web applications. One essential feature of many websites is a contact form, which allows users to get in touch with you or your business. In this tutorial, we will walk you through the process of creating a contact form in Next.js. By the end of this article, you will have a functional contact form that you can integrate into your Next.js application.
Prerequisites
Before we get started, make sure you have the following prerequisites in place:
- Node.js and npm installed on your computer.
- A basic understanding of React and Next.js.
- A Next.js project set up. If you don’t have one, you can create a new Next.js project using the following command:
npx create-next-app my-contact-form
Step 1: Create the Contact Form Component
First, let’s create a new component for our contact form. In your Next.js project, navigate to the components
directory and create a new file called ContactForm.js
. Here’s a basic structure for the contact form component:
// components/ContactForm.js
import React, { useState } from 'react';
const ContactForm = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
message: '',
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
// Handle form submission here
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
/>
</div>
<div>
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
</div>
<div>
<label htmlFor="message">Message</label>
<textarea
id="message"
name="message"
value={formData.message}
onChange={handleChange}
/>
</div>
<button type="submit">Submit</button>
</form>
);
};
export default ContactForm;
This component sets up a basic form with fields for name, email, and message. It also handles form input changes and submission.
Step 2: Create a Contact Page
Next, let’s create a page where we’ll render our contact form. In your Next.js project, navigate to the pages
directory and create a new file called contact.js
. Here’s an example of what the contact page might look like:
// pages/contact.js
import React from 'react';
import ContactForm from '../components/ContactForm';
const Contact = () => {
return (
<div>
<h1>Contact Us</h1>
<ContactForm />
</div>
);
};
export default Contact;
This page simply renders the ContactForm
component and displays a “Contact Us” heading.
Step 3: Handle Form Submission
Now that we have our contact form set up, let’s handle form submission. In the handleSubmit
function of the ContactForm
component, you can add code to send the form data to your server, an email service, or any other appropriate destination. Here’s a basic example using JavaScript’s fetch
API to make a POST request to a hypothetical server endpoint:
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch('/api/contact', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
if (response.ok) {
// Handle success, e.g., show a success message
alert('Message sent successfully!');
setFormData({ name: '', email: '', message: '' });
} else {
// Handle error, e.g., show an error message
alert('Error sending message. Please try again later.');
}
} catch (error) {
console.error('Error:', error);
}
};
In this example, we assume that you have a server endpoint at /api/contact
that can handle the form data.
Step 4: Style Your Contact Form
To make your contact form visually appealing, you can use CSS or a CSS framework like Tailwind CSS. Style your form according to your application’s design and branding.
Conclusion
In this tutorial, we’ve created a contact form in a Next.js application. You’ve learned how to create a basic form component, render it on a page, and handle form submissions. Remember that this is just the starting point, and you can customize and extend your contact form as needed for your project.