Written by: Geoffrey Callaghan
How To Create A Contact Form In Next.js
How To Create A Contact Form In Next.js
To create a contact form in Next.js with FabForm.io, you can follow these steps:
Sign Up on FabForm.io:
Create a Form:
Get the Form Endpoint:
Create a Next.js Project:
Set up a new Next.js project if you don’t have one already. You can use the following commands in your terminal:
npx create-next-app my-nextjs-app
cd my-nextjs-app
Install Axios:
Axios is a popular library for making HTTP requests. Install it using the following command:
npm install axios
Create a Contact Form Component:
Create a new file for your contact form component. For example, components/ContactForm.js
. In this file, you can create a simple form with the necessary input fields.
import { useState } from 'react';
import axios from 'axios';
const ContactForm = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
message: '',
});
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post('YOUR_FABFORM_ENDPOINT', formData);
console.log('Form submitted successfully');
} catch (error) {
console.error('Error submitting form:', error);
}
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" name="name" onChange={handleChange} />
</label>
<label>
Email:
<input type="email" name="email" onChange={handleChange} />
</label>
<label>
Message:
<textarea name="message" onChange={handleChange}></textarea>
</label>
<button type="submit">Submit</button>
</form>
);
};
export default ContactForm;
Use the Contact Form Component:
In your desired Next.js page or component, import and use the ContactForm
component.
import ContactForm from '../components/ContactForm';
const ContactPage = () => {
return (
<div>
<h1>Contact Us</h1>
<ContactForm />
</div>
);
};
export default ContactPage;
Replace ‘YOUR_FABFORM_ENDPOINT’:
'YOUR_FABFORM_ENDPOINT'
in the axios.post
call with the actual endpoint you obtained from FabForm.io.Style the Form (Optional):
Run Your Next.js App:
npm run dev
and test the contact form.By following these steps, you should be able to create a contact form in Next.js that submits data to FabForm.io. Remember to replace placeholders and customize the form and styling according to your needs.