Saturday, May 14, 2022
HomeWebsite DesignAdd a Contact Kind to a React App with Netlify Types

Add a Contact Kind to a React App with Netlify Types


On this tutorial, you’ll learn to add a contact type to a React utility with Netlify Types.

Including a contact type to a React utility would possibly require writing server-side code to deal with type submissions, however with Netlify Types you possibly can take a break from the logic, as a result of it does all that behind-the-scenes be just right for you when your web site is deployed on Netlify.

Conditions

To comply with together with this tutorial, you ought to be conversant in React, Git and GitHub. You must also have a Netlify account and have Node put in in your machine. In the event you want any assist getting arrange, you possibly can seek the advice of our information on how one can set up Node utilizing nvm.

What You’ll Be taught

By the tip of this tutorial, you’ll know how one can do the next:

  • deploy a React app to Netlify
  • combine Netlify Types with a stateless type element (a type element that doesn’t use the state)
  • combine Netlify Types with a stateful type element (a type element that makes use of the state to deal with its knowledge)

The finished information to this tutorial is on the market on GitHub.

Introduction to Netlify Types

Netlify Types is a characteristic of Netlify for managing and dealing with type submissions with out having to write down any server-side code. By including a easy attribute to your HTML type tag, you possibly can rise up and operating with Netlify Types. Types may also be submitted asynchronously with JavaScript, making it an incredible companion to websites powered by Vue, React, and different trendy frameworks.

Netlify Types Pricing

Netlify Types is free to get began with, however there’s a restrict of 100 type submissions per web site per thirty days on the free plan, and likewise some options like background capabilities and role-based entry management are excluded whereas utilizing the free tier.

To exceed the shape submission restrict or make the excluded options out there, you’ll must improve to a special plan. You are able to do that on the Netlify pricing web page.

Making a Kind for Netlify Types

Netlify Types may be built-in with each a stateless type (a type that doesn’t use the state to deal with its knowledge) and stateful one (a type that makes use of the state to deal with its knowledge). On this tutorial, we’ll firstly create a stateless type to reveal how we will combine Netlify Types with it. However in a while, we’ll refactor the stateless type right into a stateful one, wherein we’ll additionally combine with Neltify Types.

Let’s begin by creating and organising a brand new React app.

Create and arrange React

Sort the next command in your terminal to create a brand new React app:

$ npx create-react-app netlify_forms_app

Right here our app’s identify is netlify_forms_app, however you can provide it any identify you would like so long as it’s not a restricted npm identify. After the set up is full, develop into the newly created listing, then begin the app with the npm begin command in your terminal.

Let’s clear up (non-compulsory) our app a bit bit. Within the src listing of the app, delete the next recordsdata:

  • App.check.js
  • emblem.svg
  • setupTests.js

We deleted these recordsdata as a result of they aren’t related to us in our construct. We are able to additionally delete the reportWebVitals file. Doing that requires that we additionally take away the import assertion and the perform name of reportWebVitals from the index.js file for our React app to compile efficiently. Once more, that is all non-compulsory, so you possibly can simply skip this if you happen to want.

Now, clear up the App.js file in order that it appears to be like like this:


import './App.css';

perform App() {
  return (

  );
}

export default App;

Making a contact type element

Within the src listing of our React app, create a Kind.js file and add the next traces of code to it:


import './type.css'

export default perform Kind() {
  return (
    <type 
      technique='POST' 
      identify='contactform' 
      className='contactForm'>

      <enter 
        sort='textual content' 
        identify='identify' 
        placeholder='Enter your identify' />

      <enter 
        sort='electronic mail' 
        identify='electronic mail' 
        placeholder='Enter your electronic mail' />

      <textarea 
        identify='message' 
        placeholder='Messaage'></textarea>

      <button sort='submit'>Submit</button>

    </type>
  )
}

Right here, we’ve a stateless React type. Now, go to the App.js file within the src listing and render the shape. The App.js file ought to appear to be this:

import './App.css';
import Kind from './Kind'

perform App() {
  return (
    <Kind />
  );
}
export default App;

Styling the shape element with plain CSS

Within the src listing, create a type.css file and add the next fashion:

// src/type.css
.contactForm{
  padding: 10px;
  width: 90%;
  max-width: 400px;
  margin: 30px auto;
  border-radius: 10px;
  show: flex;
  flex-direction: column;
  hole: 20px;
}
.contactForm enter, button, textarea{
  peak: 50px;
  padding-left: 5px;
  font-size: 18px;
}
.contactForm textarea{
  peak: 100px;
}

There’s no want to write down any fancy CSS, however you possibly can add some tweaks if you want. With the kinds we’ve added, our HTML type now appears to be like just like the picture beneath.

A simple contact form made with React

To see the end result, you’ll want to vary into the netlify_forms_app folder and begin the server:

cd netlify_forms_app
npm begin

A browser will open up and you may view the end result at http://localhost:3000.

An ideal instance of a stateless React type is the one we created earlier. On this type, our enter values aren’t managed by the state. On this part, we’ll learn to add a contact type to a stateless React app with Netlify Types.

Including a static HTML model of the shape

Step one to enabling our type to work with Netlify Types is so as to add a static HTML model of our type to the index.html file within the public listing of our React app. Why do we have to add this manner? Including this HTML type will assist Netlify detect our JSX type, because the post-process bots can solely parse HTML.

For this instance, we’ll add this HTML type proper after the opening the <physique> tag in our index.html file:


<type identify='contactForm' netlify hidden>
  <enter sort='textual content' identify='identify' />
  <enter sort='electronic mail' identify='electronic mail' />
  <textarea identify='message'></textarea>
</type>

There are two attributes to notice on this type: identify and netlify. The identify attribute will allow Netlify to attach with our JSX type, whereas the netlify attribute will allow Nelify’s bot to have the ability to parse our type. We additionally used the hidden attribute to cover the shape from our customers. There’s no want so as to add labels or a submit button to this manner, because it’s hidden from our web site.

Add a hidden enter ingredient to the JSX type

Within the Kind.js file within the src listing, add a hidden enter ingredient with the identify attribute set to form-name and the worth attribute equal to the identify of the HTML model of our type. These attributes are required to make our type work with Netlify Types:


<enter 
  sort='hidden' 
  identify='form-name'
  worth='contactForm' />

The ultimate model of our type now appears to be like like this:


<type 
  technique='POST' 
  identify='contactform' 
  className='contactForm'>

  <enter 
    sort='hidden'
    identify='form-name'
    worth='contactForm' />

  <enter 
    sort='textual content' 
    identify='identify' 
    placeholder='Enter your identify' />

  <enter 
    sort='electronic mail' 
    identify='electronic mail' 
    placeholder='Enter your electronic mail' />

  <textarea 
    identify='message' 
    placeholder='Messaage'></textarea>

  <button sort='submit'>Submit</button>
</type>

There’s another step required for this manner to start out working: deploying our React app to Netlify. We’ll cowl this within the subsequent part.

Deploying to Netlify

We are able to deploy our web site to Netlify utilizing a model management system like GitHub, or we will use the drag-and-drop technique, which requires us to switch the construct file created from operating the npm run construct command to Netlify drag and drop web page. Each strategies of deployment can be coated within the following sections, however for this tutorial, we’re going to make use of GitHub for deployment.

Deploy with GitHub

Deploying our React app from GitHub will set us up for steady deployment, which means modifications made to our repository will routinely set off re-deployment of our web site, which is a bonus over utilizing the drag-and-drop technique.

To have the ability to deploy from GitHub, we’ve to first make our React app out there on it. Go over to GitHub and create a brand new repository.

Create a new repository page on GitHub

For this tutorial, we’ll identify the repository “NelifyForms”. Now on the backside of the web page, click on the Create Repository button and we’ll be redirected to the newly created repository web page.

Created new repository

Proper now, this repository is empty. That’s as a result of we haven’t pushed our React app to it. To do this, enter the next instructions within the terminal:

$ git add *
$ git commit -m 'netlify kinds with stateless type'
$ git distant add origin <Your_repoistory's_url>
$ git push -u origin grasp

These instructions will create a brand new commit, join us to our GitHub repository, and eventually push our React app over to it.

Be certain that to switch with the URL of the newly created GitHub repository. Right here’s a picture that exhibits the place to seek out the URL of the newly created repository.

Repositories URL

After operating the above git instructions, refresh the browser. You’ll discover that our React app has been pushed to GitHub.

NetlifyForms repository

Now that our React app is on the market on GitHub, it’s time that we deployed it on Netlify. Log in to your Netlify account, go over to the dashboard, and click on on the New web site from Git button. We’ll be taken to the Create a brand new web site web page.

Create a new site page

Click on on the GitHub button underneath the Steady Deployment part. We’re then redirected to an authorization web page the place Netlify will ask for entry to GitHub. After giving Netlify entry, we’ll see a web page just like the one proven beneath.

Create a new site page

Proper now, the NetlifyForms repository we created earlier shouldn’t be displaying among the many listing of repositories, as a result of we haven’t configured Netlify to entry it but.

To do this, click on on the Configure the Netlify app on GitHub hyperlink on the backside of the web page. We’ll see a web page just like the one proven beneath.

Configuration page for Netlify on GitHub

Scroll to the underside of the web page underneath the Repositories entry part and click on on the Choose repositories button. We’ll see an inventory of our GitHub repositories.

Configuration page for Netlify on GitHub

Choose the NelifyForms repository after which click on on save to offer Netlify entry to this repository. After saving it, we’ll be redirected to the Create a brand new web site web page on Netlify.

Create a new site page on Nelify

Our NetlifyForms repository is now displayed within the listing. Click on on it and we’ll see a web page like this.

Site build and deployment page

On this web page, we will set the construct and deployment choices for our web site, like altering the Git department to deploy from, or the command for use to deploy our web site. However there can be no want for that, as a result of every part appears to be like good by default.

Lastly, to deploy our web site to Netlify, scroll to the underside of the web page and click on on the Deploy web site button. The deployment would possibly take some time, however as soon as it’s finished we’ll see a hyperlink to our web site on the prime proper nook of the positioning dashboard web page.

Sites URL

With this, our React app has been efficiently deployed to Netlify from GitHub. Once we click on on the hyperlink, we’ll see the React type we constructed.

React form

Deploy utilizing drag and drop

Deploying with this technique is less complicated, however the disadvantage is that our web site gained’t be arrange for steady deployment. We are able to set this up manually after deployment if our React app is on the market on both GitHub, GitLab, or Bitbucket.

To make use of the drag-and-drop technique we’ve to first construct our React app. Open the terminal and navigate to the listing the place our React app is, then sort within the following command:

$ npm run construct

As soon as the construct is completed, there must be a brand new folder named construct current within the root listing of the React app. Our listing construction will now appear to be this:

> construct
> node_modules
> public
> src

What’s left now could be to pull and drop this folder to Netlify’s drag and drop web page.

Netlify's drag and drop page

We are able to do this by navigating to the situation of our React app in our programs file explorer, then drag and drop the construct folder to Netlify’s drag and drop web page.

Right here’s a GIF that illustrates simply that.

Drag and drop gif

As soon as we’ve drag and dropped the construct folder to Netlify, will probably be uploaded and deployed. Then we’ll be redirected to our web site’s dashboard web page. The URL to the deployed web site is positioned on the prime proper nook of the web page.

Site dashboard page

Click on on that URL and also you’ll see the contact type we constructed. Fill within the type and hit the Submit button. You’ll be redirected to a Thanks affirmation web page.

confirmation page

Cool! We’ve efficiently made our stateless React type work with Netlify Types. Now each type submission made via our app is dealt with by Netlify Types.

Proper now, we aren’t receiving any notifications by way of electronic mail when a brand new type is submitted, as a result of we haven’t set the e-mail tackle type submissions can be despatched to. We’ll cowl that shortly.

Managing contact type submissions

Not solely does Netlify make including a contact type easy, but it surely additionally consists of options the place submissions made via our contact type may be deleted, marked as spam, or downloaded. There’s additionally room to combine our type with Netlify’s serverless capabilities. You’ll be able to examine it right here.

To entry the submission administration web page, go over to the sooner deployed web site dashboard web page on Netlify and click on on the Kind hyperlink within the navigation bar.

Site dashboard page

After clicking on the Kind hyperlink, you’ll be redirected to the shape dashboard web page.

Form dashboard page

Click on on contactForm underneath the Lively kinds part to view the administration web page of submissions made via our contact type.

Including Notification and Customized Affirmation Pages

On this part, we’ll cowl how one can add a notification characteristic that can allow us to obtain electronic mail notifications for brand new type submissions. We’ll additionally cowl how one can customise the Thanks affirmation web page that exhibits up after the shape has been efficiently submitted.

Receiving notifications by way of electronic mail

Within the dashboard of our web site, navigate to Website settings > Types > Kind notifications. Then click on on the Add notification button. A menu will pop up.

Form notification

Netlify offers us three choices on how we will obtain notifications. On this tutorial, we’re going to make use of the e-mail notification.

Click on on E mail notification and fill out the shape that seems.

Form for receiving notification via email

The sector we’re extra involved with is the E mail to inform subject. Be certain that to enter the e-mail tackle you’d prefer to obtain electronic mail notifications on.

Now once we open our deployed web site URL and make a brand new type submission, we must always obtain an electronic mail notification.

Customizing the affirmation web page

To customise the affirmation web page, step one is so as to add an motion attribute to the type ingredient of the index.html file within the public listing:

// public/index.htmm
<type identify="contactForm" netlify motion="/confirmation-page" hidden>
...

We’ve set the motion attribute to equal /confirmation-page. It will inform Netlify to redirect to this web page after a type has been submitted. Though there can be a redirection to the affirmation web page, there gained’t be a change within the URL path. To additionally change the URL path, we additionally want so as to add the motion attribute to the JSX type within the Kind.js file:


...
<type 
  technique='POST' 
  identify='contactform' 
  className='contactForm'
  motion='/confirmation-page'>
...

As soon as we’ve finished this, the following factor is to create a affirmation web page.

Within the public listing of our React app, create a confirmation-page.html file and add the next line of code:


<!DOCTYPE html>
<html lang="en" >
  <head>
    <meta charset="utf-8">
    <title>confirmation0 web page</title>
  </head>
  <physique>
    <div fashion='text-align: middle; font-size:1.5rem;'>
      <h2>Thanks</h2>
      <small>You'll be replied to shortly</small>
    </div>
  </physique>
</html>

To check if the affirmation web page works, we’ve to re-deploy our web site. It’s a great factor we deployed our web site from GitHub. All we’ve to do now to re-deploy it’s to write down a number of Git instructions, and voila! Our web site can be routinely re-deployed on Netlify.

Listed here are the instructions:

$ git add *
$ git commit -m 'added affirmation web page'
$ git push

These instructions create a brand new commit and modify our GitHub repository. Since we’ve linked Netlify to the NetlifyForms repository on GitHub, when a modification is made to it, Netlify instantly notices that modification and re-deploys our web site.

As soon as our web site has been re-deployed and we’ve made a brand new type submission, we’ll see the affirmation web page.

Customized confirmation page

Kind Dealing with in a Stateful React Kind

On this part, we’ll learn to add a contact type to a stateful React app with Netlify Types utilizing class-based parts and React hooks.

We’re going to make use of the shape we created within the “Kind Dealing with with a Stateless React Contact Kind” part.

Notice: on this part, we gained’t cowl deployment or how one can obtain electronic mail notifications. We’ve already coated that in earlier sections.

Kind dealing with with class-based parts

To make use of the shape we created within the earlier part (to reveal how we will use Netlify type with a stateful React type), we first have to vary the shape from a stateless type to a stateful one.

The Kind.js file ought to appear to be this:


import './type.css'
import {Part} from 'react'

export default class Kind extends Part{
  constructor(props){
    tremendous(props)
    this.state = { identify: '', electronic mail: '', message: '' }
  }

  handleChange = e =>
    this.setState({ [e.target.name]: e.goal.worth })

  render() {
    const { identify, electronic mail, message } = this.state
    return (
      <type className='contactForm' >

        <enter 
          sort='textual content' 
          identify='identify' 
          worth={identify}
          placeholder='Enter your identify'
          onChange={this.handleChange} />

        <enter 
          sort='electronic mail' 
          identify='electronic mail' 
          worth={electronic mail}
          placeholder='Enter your electronic mail'
          onChange={this.handleChange} />

        <textarea 
          identify='message' 
          placeholder='Messaage'
          worth={message}
          onChange={this.handleChange}></textarea>

        <button sort='submit'>Submit</button>
      </type>
    )
  }
}

The subsequent step is to create a technique that can be chargeable for posting type submissions. To do this, we’ve to first add an onSubmit occasion listener to the shape:


...
<type 
  className='contactForm' 
  onSubmit={this.handleSubmit}>
...

Now, let’s create the handleSubmit technique, which is able to submit new type submissions to Netlify Types.

Add the next code after the handleChange technique within the Kind element:


...
handleSubmit = e => {
  fetch("https://www.sitepoint.com/", {
    technique: 'POST',
    headers: { 'Content material-Sort': 'utility/x-www-form-urlencoded' },
    physique: encode({ 'form-name': 'contactForm', ...this.state })
  })
    .then(() => alert('Success!'))
    .catch(error => alert(error))
  e.preventDefault()
}
...

Discover that, within the physique of the request, we used an encode perform. We’ll create it shortly. This perform encodes particular characters (?, =, /, &) within the type earlier than posting it.

Lastly, add the next traces of code earlier than the Kind element:

...
const encode = (knowledge) => {
  return Object.keys(knowledge)
    .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(knowledge[key])).be a part of('&');
}
...

Our Kind.js file ought to now appear to be this:


import './type.css'
import {Part} from 'react'

const encode = (knowledge) => {
  return Object.keys(knowledge)
    .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(knowledge[key])).be a part of('&');
}

export default class Kind extends Part{
  constructor(props){
    tremendous(props)
    this.state = { identify: '', electronic mail: '', message: '' }
  }

  handleChange = e =>
    this.setState({ [e.target.name]: e.goal.worth })

  handleSubmit = e => {
    fetch("https://www.sitepoint.com/", {
      technique: 'POST',
      headers: { 'Content material-Sort': 'utility/x-www-form-urlencoded' },
      physique: encode({ 'form-name': 'contactForm', ...this.state })
    })
      .then(() => alert('Success!'))
      .catch(error => alert(error))
    e.preventDefault()
  }

  render() {
    const { identify, electronic mail, message } = this.state
    return (
      <type 
        className='contactForm' 
        onSubmit={this.handleSubmit}>
        <enter 
          sort='textual content' 
          identify='identify' 
          worth={identify}
          placeholder='Enter your identify'
          onChange={this.handleChange} />

        <enter 
          sort='electronic mail' 
          identify='electronic mail' 
          worth={electronic mail}
          placeholder='Enter your electronic mail'
          onChange={this.handleChange} />

        <textarea 
          identify='message' 
          placeholder='Messaage'
          worth={message}
          onChange={this.handleChange}></textarea>

        <button sort='submit'>Submit</button>
      </type>
    )
  }
}

This manner will solely work correctly if we’ve deployed and arrange electronic mail notifications for it. This was coated in earlier sections.

Kind dealing with with React hooks

The React hook we’re going to make use of on this part is the useState hook. The useState hook will allow us to add state to a practical element.

To make use of the useState hook within the Kind element we created earlier, we first have to import the useState hook, then remodel the class-based Kind element right into a practical element.

The Kind.js file ought to appear to be this:


import './type.css'
import {useState} from 'react'

const encode = (knowledge) => {
  return Object.keys(knowledge)
    .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(knowledge[key])).be a part of('&');
}

export default perform Kind (){
  const [state, setState] = useState({identify: '', electronic mail: '', message: '' })

  const handleChange = e =>
    setState({...state, [e.target.name]: e.goal.worth })

  const handleSubmit = e => {
    fetch("https://www.sitepoint.com/", {
      technique: 'POST',
      headers: { 'Content material-Sort': 'utility/x-www-form-urlencoded' },
      physique: encode({ 'form-name': 'contactForm', ...state })
    })
      .then(() => alert('Success!'))
      .catch(error => alert(error))
    e.preventDefault()
  }

  return (
    <type 
      className='contactForm' 
      onSubmit={handleSubmit}>

      <enter 
        sort='textual content' 
        identify='identify' 
        worth={state.identify}
        placeholder='Enter your identify'
        onChange={handleChange} />

      <enter 
        sort='electronic mail' 
        identify='electronic mail' 
        worth={state.electronic mail}
        placeholder='Enter your electronic mail'
        onChange={handleChange} />

      <textarea 
        identify='message' 
        placeholder='Messaage'
        worth={state.message}
        onChange={handleChange}></textarea>
      <button sort='submit'>Submit</button>
    </type>
  )
}

Now, deploy and arrange electronic mail notifications for the contact type to start out working.

Conclusion

I hope you’ve discovered this straightforward contact type tutorial helpful. I hope you’ll agree that Netlify affords a viable choice for including a contact type to your React app — one which saves you time and saves you having to take care of server-side coding. Be happy to get in contact on Twitter when you have any questions.

Troubleshooting ideas

In the event you run into any issues whereas working with kinds in Netlify, head over to Netlify’s helpful Troubleshooting ideas.

References



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments