How to Add a Netlify Form to a React App Built with create-react-app

React and Netlify logos

If you‘re building a web application with React, chances are you‘ll need a way for users to submit data, whether that‘s through a contact form, survey, registration, or order process. While you can build your own backend API to handle form submissions, using Netlify forms is a much simpler solution that doesn‘t require any server-side code.

In this in-depth tutorial, we‘ll walk through the process of adding a Netlify form to a React application generated with create-react-app. By the end, you‘ll have a fully functioning form that you can customize and extend for your needs.

Why Use Netlify for React Apps?

Netlify is a popular platform for deploying and hosting web applications. Over 1,500,000 developers and businesses use Netlify, including major companies like Google, Facebook, Verizon, and Unilever.

There are many benefits to using Netlify, especially for React applications:

  • Easy deployment: You can connect your Git repository and deploy your React app with just a few clicks. Netlify will automatically build and deploy your app whenever you push changes.
  • Serverless functions: Netlify provides serverless backend services, so you can add API endpoints and form handling without managing a separate server.
  • Custom domains and SSL: You can easily use a custom domain with your Netlify site and get a free SSL certificate applied automatically.
  • Global CDN: Netlify‘s intelligent CDN will distribute your content around the world for fast loading times.
  • Generous free tier: The free tier includes all the core features and enough usage for most small to medium sites.

Specifically for forms, Netlify offers some key advantages:

  • No backend code required: Netlify automatically detects forms in your React app and handles the submission process for you.
  • Manage submissions in Netlify: All form submissions are stored in your Netlify account and can be viewed, downloaded, or triggered via webhook.
  • Spam filtering: Netlify provides a few different spam filtering options, including honeypot fields and reCAPTCHA 2.
  • Email notifications: You can set up email notifications for new form submissions, so you‘re always up-to-date.
  • Customize with serverless functions: For more advanced processing and integrations, you can access form submission data in a serverless function.

Creating a React App with create-react-app

The first step is to generate a new React app using create-react-app. This requires Node.js, so if you don‘t have that installed already, download it from the official site.

Open up your terminal and navigate to the directory where you want to create your project. Then run:

npx create-react-app netlify-forms-example
cd netlify-forms-example

This will generate a new React project in the netlify-forms-example directory and navigate you into it.

To start the development server and see the default page, run:

npm start

You should now be able to open http://localhost:3000 and see the spinning React logo.

React default page

Adding a Form Component

Now let‘s add a form to our React app. We‘ll create a new component for this.

Create a new file src/Form.js and add the following:

import React from "react";

export default function ContactForm() {
  return (
    <form name="contact" method="POST" data-netlify="true">
      <p>
        <label htmlFor="name">Name</label>
        <input type="text" name="name" id="name" />
      </p>
      <p>
        <label htmlFor="email">Email</label>  
        <input type="email" name="email" id="email" />
      </p>
      <p>
        <label htmlFor="message">Message</label>
        <textarea name="message" id="message"></textarea>
      </p>
      <p>
        <button type="submit">Send</button>
      </p>
    </form>
  );
}

This is a simple form with fields for name, email, and message.

The key things to note for Netlify forms:

  • The form must have a name attribute. This will identify the form in the Netlify dashboard.
  • The form needs the netlify attribute to be detected by Netlify.
  • Each field must have a name attribute. These will be the keys in the submission data.

Now let‘s include this form in our main App component. Update src/App.js like so:

import ‘./App.css‘;
import ContactForm from ‘./Form‘;

function App() {
  return (
    <div className="App">

      <ContactForm />
    </div>
  );
}

export default App;

The page should now show our contact form:

React app with form

Setting Up Netlify

Before we can deploy our app and start accepting form submissions, we need to make a few additions to our project for Netlify.

First, add a public/_redirects file with the following:

/* /index.html 200

This tells Netlify to always serve the index.html file for any URL, which is necessary for client-side routing in React.

We also need to create a production build of our app. Stop the development server if it‘s still running, and run:

npm run build  

This will create an optimized production build in the build directory.

Finally, to make our form detectable by Netlify, we need to add a hidden form to our public/index.html file. Right before the closing </body> tag, add:

<form name="contact" netlify netlify-honeypot="bot-field" hidden>
  <input type="text" name="name" />      
  <input type="email" name="email" />
  <textarea name="message"></textarea>
</form>

This is almost the same as our form component, but with a few key differences:

  • It has the netlify attribute
  • It has a netlify-honeypot attribute, which is used to prevent spam submissions
  • It has a hidden attribute so it won‘t be visible on the page
  • It doesn‘t have the submit button

Also add a hidden input to the form in src/Form.js:

<input type="hidden" name="form-name" value="contact" />

The value should match the name of our form.

Deploying to Netlify

We‘re now ready to deploy our app to Netlify and start accepting form submissions.

If you haven‘t already, create a Netlify account. There‘s a generous free tier that will be more than enough for this example.

Once you‘re logged in, click the "New site from Git" button. You can choose to connect your Git provider, but for this example, we‘ll just drag and drop our project folder.

Navigate to your project in your terminal and run:

npm run build

This will create a production build in the build folder.

Drag and drop the build folder into the Netlify window. It will upload the files and deploy your site on a random URL.

Netlify drag and drop deploy

Once the deploy is finished, you should see a notice that your form has been detected:

Netlify form detected

Click the link to see your deployed site and try submitting the form. The submissions will show up in your Netlify dashboard under Forms.

How Netlify Forms Work

So what‘s actually happening when a user submits the form? Let‘s break it down.

When Netlify deploys your site, it scans the HTML files for forms with the netlify attribute. It then sets up handling for those forms.

When a user submits the form, the browser sends a POST request to Netlify‘s servers with the form data. Netlify then processes the submission, checking for spam and running any integrations or notifications you‘ve set up.

The form submissions are stored in your Netlify account. You can view and manage them through the Forms tab in your site dashboard.

Netlify also provides an API for retrieving form submissions programmatically. You could use this to display submissions on your site, or to integrate with other services.

Netlify Forms vs Other Solutions

Netlify forms are just one way to handle form submissions in a React app. Let‘s compare it to a few other common solutions:

Solution Pros Cons
Netlify Forms – No backend code required
– Easy to set up and manage
– Spam filtering and notifications built-in
– Limited customization
– Tied to Netlify hosting
– File uploads require paid plan
Custom Backend – Complete control and customization
– Can use any hosting provider
– Integrate with any services
– Have to build and maintain backend
– More complex setup
– Manage scaling and security
Form Service (e.g. Formspree, FormKeep) – No backend code required
– Work with any static site
– More customization than Netlify
– Separate service to manage
– Usually requires subscription for advanced features
– May not have spam filtering

In general, Netlify forms are a great choice if you‘re already using Netlify to host your React app and you have fairly standard form requirements. If you need more customization or aren‘t using Netlify, a form service or custom backend may be a better fit.

Advanced Usage and Customization

While this tutorial covered the basics of setting up a Netlify form in a React app, there‘s a lot more you can do with Netlify forms. Some advanced use cases and customizations:

  • Spam filtering: In addition to the honeypot field, you can add reCAPTCHA 2 to your forms for extra spam prevention. See the Netlify docs for setup instructions.

  • Email notifications: Netlify can send email notifications when a form is submitted. Configure this in the Forms tab of your site dashboard.

  • Slack notifications: You can also set up Slack notifications for new form submissions. This is a great way to get real-time alerts and collaborate with your team.

  • Custom submission page: By default, Netlify will display a generic success message after a form is submitted. You can customize this by creating a success.html page and specifying the path in your form‘s action attribute.

  • Serverless functions: For more advanced integrations, you can use a Netlify serverless function to process the form data. The form data will be sent to the function, where you can run custom logic, save to a database, send notifications, etc.

  • Styling and validation: Netlify leaves the form styling and client-side validation up to you. You can use CSS to style your form, and JavaScript to add validation before the form is submitted.

  • File uploads: Netlify forms support file uploads, but this requires upgrading to a paid plan. Files are stored in AWS S3 and can be accessed via the Netlify API.

Netlify Forms FAQs

Here are answers to some common questions about using Netlify forms in a React app:

Can I use Netlify forms without using Netlify hosting?

No, Netlify forms are only available for sites hosted on Netlify. If you‘re not using Netlify to host your React app, you‘ll need to use a different solution for handling form submissions.

Do I need to use the Netlify CLI to use forms?

No, you don‘t need to use the Netlify CLI to use forms. As long as your React app is deployed to Netlify and your forms are set up correctly, Netlify will handle the form submissions.

Why do I need to add a hidden form to my HTML?

The hidden form is how Netlify detects and sets up handling for your form. When Netlify deploys your site, it scans the HTML for forms with the netlify attribute, and the hidden form is what it finds.

How can I access form submissions in my React app?

Netlify provides an API for retrieving form submissions. You can use this in your React app to display submissions or integrate with other services. Check the Netlify docs for instructions on using the API.

How much do Netlify forms cost?

Netlify forms are included in all plans, even the free tier. The free tier allows 100 submissions per month, which is plenty for most small to medium sites. If you need more submissions or features like file uploads, you can upgrade to a paid plan.

Conclusion

In this tutorial, we‘ve seen how to add a Netlify form to a React app created with create-react-app. The process involves:

  1. Creating a new React app with create-react-app
  2. Adding a form component
  3. Linking the form to Netlify with a few attributes and a hidden form
  4. Deploying the app to Netlify
  5. Viewing and managing form submissions in the Netlify dashboard

Netlify forms are a powerful and easy-to-use solution for handling form submissions in a React app, without needing to write any backend code. With features like spam filtering, email notifications, and serverless function integration, Netlify forms can handle a wide variety of use cases.

However, Netlify forms may not be the best solution for every project. If you need more control and customization, or if you‘re not using Netlify to host your React app, you may want to consider a custom backend or a standalone form service.

Hopefully this tutorial has given you a solid understanding of how to use Netlify forms in your React projects. From here, you can customize and extend your forms to fit your specific needs. Happy coding!

Additional Resources

Similar Posts