Contact Form for Next.js
Code example and implementation of a contact form for Next.js
Next.js Contact Form Code Example
This is an example of a contact form for a Next.js app. Next.js is a framework for building Universal JavaScript Applications using React. It's easy to get started, scales beautifully, and supports custom routing with the same API as React Router.
import { useState } from "react";
export default function Form() {
const [responseMessage, setResponseMessage] = useState("");
async function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
const object = Object.fromEntries(formData);
const json = JSON.stringify(object);
const response = await fetch("https://formbold.com/s/unique_form_id", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: json,
});
const result = await response.json();
if (response.ok) {
setResponseMessage(result.message);
event.target.reset();
}
setResponseMessage(result.message || "Something went wrong");
setTimeout(() => setResponseMessage(""), 3000);
}
return (
<>
<div className="container">
<div className="form-wrapper">
<form onSubmit={handleSubmit}>
<div>
<input
type="email"
name="email"
id="email"
placeholder="Your Email"
required
/>
</div>
<div>
<input
type="text"
name="subject"
id="subject"
placeholder="Your subject"
required
/>
</div>
<div>
<textarea
name="message"
id="message"
rows="6"
placeholder="Your Message"
required
></textarea>
</div>
<div>
<button type="submit">Submit</button>
</div>
<div>
<p>{responseMessage}</p>
</div>
</form>
</div>
</div>
</>
);
}