Home > Web Front-end > CSS Tutorial > How to Create a Contact Form With Next.js and Netlify

How to Create a Contact Form With Next.js and Netlify

尊渡假赌尊渡假赌尊渡假赌
Release: 2025-03-18 11:05:12
Original
393 people have browsed it

Build efficient contact forms with Next.js and Netlify and integrate powerful spam detection! This article will guide you to create a contact form with a confirmation page and use Netlify's built-in capabilities to improve anti-spam capabilities.

How to Create a Contact Form With Next.js and Netlify

Next.js is a powerful React framework that can build high-performance, scalable React applications. Combined with Netlify, you can quickly build a contact form without writing server-side code.

Netlify forms are convenient to set up and the free version is available (each Netlify site can submit a form up to 100 free times). Submitted forms are automatically passed through Netlify's built-in spam filter (using Akismet) and offer a variety of configuration options to enhance spam detection.

Create a contact form

In the Next.js application, create a ContactForm component to render forms on the contact page. If you want the form to render under the /contact path, you should use the following ContactForm component in pages/contact.js file, including the tags and input fields:

 const ContactForm = (/* code see */ below);
Copy after login

The following code snippet creates a form with name, company, email and message fields, and a submit button. After submitting the form, it will be redirected to /contact/?success=true according to the form's action attribute value. Currently, there is no difference in how the page looks when it comes with and without success query parameters, and we will update it later.

The current Contact.js file is as follows:

 import React from "react";
const ContactPage = () => {
 const ContactForm = (/* code in the above code snippet*/)

 Return (
   <div>
     <h1>Contact Us</h1>
     {ContactForm}
   </div>
 );
};

export default ContactPage;
Copy after login

Once we have finished setting up the basic form, we need to add some information so that Netlify automatically recognizes the form in future site deployments. To do this, you need to update the form, add data-netlify="true" property and a hidden input field containing the form name. In the Netlify dashboard, navigate to your site and click the Forms tab to view the form response based on the name set in the hidden field. Importantly, if there are multiple forms in the site, you should set a unique name for each form so that Netlify records correctly.

 {/* See below for code*/}
Copy after login
Copy after login

After successfully deploying the site to Netlify and adding the data-netlify attribute and form-name field, you can access the deployed site and fill in the form. After submitting the form, navigate to https://app.netlify.com/sites/site-name/forms (where site-name is your site name), and if the form is set successfully, the latest form submission history should be displayed.

Redirect to the confirmation page

To improve the user experience, we should add some logic to redirect to the confirmation page after the form is submitted when the URL changes to /contact/?success=true . You can also choose to redirect to a completely different page when the form is submitted, but using query parameters can use Next Router to achieve a similar effect. We can create a new variable to determine the visibility of the confirmation page or form based on the query parameters. You can use the next/router import { useRouter } from "next/router"; to retrieve the current query parameters.

 const router = useRouter();
const confirmationScreenVisible = router.query?.success && router.query.success === "true";
Copy after login

In this example, it is not possible to be visible on the page and form at the same time; therefore, you can use the following statement to determine whether the form is visible:

 const formVisible = !confirmationScreenVisible;
Copy after login

To give users the option to resubmit the form, you can add a button to the confirmation page to reset the form by clearing the query parameters. Using router.replace (rather than router.push ) not only updates the page, but also replaces the current page with a version that does not contain query parameters.

 router.replace("/contact", undefined, { shallow: true })
Copy after login

We can then render the form conditionally based on whether it is visible or not:

 {formVisible? ContactForm: ConfirmationMessage}
Copy after login

Based on the above, we can use the following code to render the form conditionally based on query parameters (updated when form is submitted):

 import React, { useState } from "react";
import { useRouter } from "next/router";

const ContactPage = () => {
 const [submitterName, setSubmitterName] = useState("");
 const router = useRouter();
 const confirmationScreenVisible =
   router.query?.success && router.query.success === "true";
 const formVisible = !confirmationScreenVisible;

 const ConfirmationMessage = (
   
     

Thank you for submitting the form. We will contact you within 24-48 hours.

); const ContactForm = (/* code in the first code example*/); Return (

Contact Us

{formVisible? ContactForm: ConfirmationMessage}
); }; export default ContactPage;
Copy after login

Add hidden robot fields

Now that the core functionality of the form is complete, we can add additional spam detection to the form in addition to the Akismet included by default. This feature can be enabled by adding data-netlify-honeypot="bot-field" property to the form.

 {/* See below for code*/}
Copy after login
Copy after login

We also need to create a new hidden paragraph with a tag called bot-field that contains the input. This field is "visible" to the robot, but not to humans. When this hidden field is filled in, Netlify detects the bot and marks the submission as spam.

<p hidden>
  <label>Please do not fill in this item:</label>
  <input type="text" name="bot-field">
</p>
Copy after login

Further customization

  • We can explore another spam protection option supported by Netlify, which is to add reCAPTCHA 2 to Netlify forms.
  • We can update the form and allow uploading of files.
  • We can set notifications for form submissions. This can be set in https://app.netlify.com/sites/[your-site-name]/settings/forms where we can include a custom topic field (can be hidden) for email notifications.

Complete code

The complete site code is available on GitHub. (Please provide a GitHub link if there is one in the article)

Extra content

The following code contains everything we discussed, as well as the logic to set up custom subject lines using what is submitted in the Name field. (Please provide the code)

Please note that the above code snippet needs to be supplemented with the complete code according to the original document. I tried my best to rewrite and polish based on the original document, striving to make pseudo-original creation without changing the original meaning.

The above is the detailed content of How to Create a Contact Form With Next.js and Netlify. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template