Write a contact form component using Nextjs
- User
Write a contact form component using Nextjs
- Assistant
Write a contact form component using Nextjs
Creating a contact form component in a Next.js application involves a combination of React for the frontend component and potentially an API route for handling form submissions if you want to process data server-side. Here’s a basic example of how you might implement such a component:
First, let's create a simple contact form component using React. This will include fields for a name, email, and message.
// components/ContactForm.js
import { useState } from 'react';
const ContactForm = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
message: '',
});
const [formStatus, setFormStatus] = useState(null);
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value,
});
};
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) {
setFormStatus('Message sent successfully!');
setFormData({
name: '',
email: '',
message: '',
});
} else {
setFormStatus('Failed to send message.');
}
} catch (error) {
setFormStatus('An error occurred.');
}
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
required
/>
</div>
<div>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
name="email"
value={formData.email}
onChange={handleChange}
required
/>
</div>
<div>
<label htmlFor="message">Message:</label>
<textarea
id="message"
name="message"
value={formData.message}
onChange={handleChange}
required
/>
</div>
<button type="submit">Send</button>
{formStatus && <p>{formStatus}</p>}
</form>
);
};
export default ContactForm;
Next.js provides a convenient way to create API endpoints. Create a new API route to handle the form submission:
// pages/api/contact.js
export default async function handler(req, res) {
if (req.method === 'POST') {
const { name, email, message } = req.body;
// You can add logic here to process/store the data, such as:
// - Send an email through a service like SendGrid, Mailgun, etc.
// - Store the message in a database
// - Log it for further usage
console.log('Received contact form submission:', { name, email, message });
// Example: Respond with a success message
res.status(200).json({ message: 'Message received' });
} else {
// Handle any other HTTP method
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
Finally, you can use this component in any page within your Next.js application:
// pages/contact.js
import ContactForm from '../components/ContactForm';
const ContactPage = () => {
return (
<div>
<h1>Contact Us</h1>
<ContactForm />
</div>
);
};
export default ContactPage;
This example is a simple contact form implementation using Next.js. You can expand upon it by adding validation, integrating it with a back-end mail service or database, and enhancing the styling using CSS or a component library. The API route provided can be adapted to perform more complex operations based on your application's requirements.
Not yet included in a published release.