Giter VIP home page Giter VIP logo

react-netlify-forms's Introduction

react-netlify-forms

React components and hooks giving you the power of Netlify Forms. Start building serverless forms on Netlify with React. Honeypot fields and reCAPTCHA are included as ready-to-use components.

NPM minzipped package size JavaScript Style Guide License

Features

It gives you all the features of Netlify Forms as simple and reusable React components which have been tested on Netlify.

  • Default form handlers with support for file uploads.
  • Spam prevention through included honeypot and reCAPTCHA components.
  • Can be used alone or together with form libraries such as Formik or react-hook-form.

Before using

This component must be used with Server-Side Rendering (SSR) because Netlify searches for a data-netlify attribute on HTML form tags to setup their Forms backend for you.

➡️ Suggestions for SSR: GatsbyJS, Next.js, react-static

Install

Either install with NPM via:

npm install --save react-netlify-forms

or with YARN via:

yarn add react-netlify-forms

Usage

In the following example a contact form with two inputs and a honeypot for extra spam prevention is shown. It also works without JavaScript by falling back to a serverside-rendered form which just submits data with an usual POST request:

import React from 'react'
import { NetlifyForm, Honeypot } from 'react-netlify-forms'

const ContactForm = () => (
  <NetlifyForm name='Contact' action='/thanks' honeypotName='bot-field'>
    {({ handleChange, success, error }) => (
      <>
        <Honeypot />
        {success && <p>Thanks for contacting us!</p>}
        {error && (
          <p>Sorry, we could not reach our servers. Please try again later.</p>
        )}
        <div>
          <label htmlFor='name'>Name:</label>
          <input type='text' name='name' id='name' onChange={handleChange} />
        </div>
        <div>
          <label htmlFor='message'>Message:</label>
          <textarea
            type='text'
            name='message'
            id='message'
            rows='4'
            onChange={handleChange}
          />
        </div>
        <div>
          <button type='submit'>Submit</button>
        </div>
      </>
    )}
  </NetlifyForm>
)

export default ContactForm

For more examples please browse through our website.

License

MIT © Björn Clees


Thanks to create-react-library for providing quick setup for NPM packages.

react-netlify-forms's People

Contributors

dependabot[bot] avatar pyrax avatar semantic-release-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-netlify-forms's Issues

Form won't submit on Gatsby.js

Hi, I'm using react-hook-form alongside with Gatsby.js. I followed the code in the docs, but it won't submit.. Here is my code..

import React, { useState } from "react"
import {
  useNetlifyForm,
  NetlifyFormProvider,
  NetlifyFormComponent,
  Honeypot,
} from "react-netlify-forms"
import { useForm } from "react-hook-form"
import tw, { styled } from "twin.macro"

const FormContainer = styled.div`
  ${tw`mt-8`};

  form {
    ${tw`flex flex-col justify-center`}
    input,
    textarea {
      border-bottom: 5px solid #282828;
      border-left: 5px solid #282828;
      padding: 10px;
      transition: all 0.3s ease;

      ${tw`w-full focus:outline-none`}
    }
    input {
      height: 50px;
    }

    input::placeholder,
    textarea::placeholder {
      color: #666;
      ${tw`font-semibold uppercase text-xs`}
    }

    p {
      color: #ff2020;
      ${tw`font-semibold text-xs mt-3`}
    }

    input.error,
    textarea.error {
      border-bottom: 5px solid #ff2020;
      border-left: 5px solid #ff2020;
    }

    div:not(:last-child) {
      ${tw`mb-8`}
    }

    textarea {
      height: 8rem;
    }

    button {
      ${tw`uppercase font-semibold text-center p-2`}
    }
  }

  h4 {
    ${tw`text-xl font-semibold`}
  }

  @media ${props => props.theme.screens.lg} {
    min-height: 450px;
  }
`

const Form = () => {
  const { register, errors, handleSubmit, formState } = useForm({
    mode: "onChange",
  })

  const netlify = useNetlifyForm({
    name: "react-hook-form",
    action: "/thanks",
    honeypotName: "bot-field",
    onSuccess: (response, context) => {
      console.log("Successfully sent form data to Netlify Server")
    },
  })

  const { isSubmitting } = formState

  const [visibleForm, clearVisibleForm] = useState(true)

  const onSubmit = data => netlify.handleSubmit(null, data)

  return (
    <FormContainer>
      {!visibleForm && (
        <>
          <h4>Thank you for contacting us! We will get back to you shortly!</h4>
        </>
      )}
      {visibleForm && (
        <NetlifyFormProvider {...netlify}>
          <NetlifyFormComponent onSubmit={handleSubmit(onSubmit)}>
            <Honeypot />
            <div>
              <input
                type="text"
                id="name"
                name="name"
                placeholder="ENTER YOUR NAME"
                className={errors.name ? "error" : ""}
                ref={register({
                  required: "Name is required",
                  minLength: {
                    value: 2,
                    message: "Name must be atleast 2 characters",
                  },
                  maxLength: {
                    value: 100,
                    message: "Name should not be more than 100 characters",
                  },
                })}
              />
              {errors.name && errors.name.message && (
                <p>{errors.name.message}</p>
              )}
            </div>
            <div>
              <input
                id="email"
                name="email"
                type="email"
                placeholder="ENTER YOUR EMAIL"
                className={errors.email ? "error" : ""}
                ref={register({
                  required: "Email is required",
                  pattern: {
                    value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
                    message: "Invalid email address.",
                  },
                })}
              />
              {errors.email && errors.email.message && (
                <p>{errors.email.message}</p>
              )}
            </div>
            <div>
              <input
                type="text"
                id="phone"
                name="phone"
                placeholder="PHONE NUMBER"
                className={errors.phone ? "error" : ""}
                ref={register({
                  required: "Phone number is required",
                  pattern: {
                    value: /\+65(6|8|9)\d{7}/g,
                    message: "Invalid phone number.",
                  },
                })}
              />
              {errors.phone && errors.phone.message && (
                <p>{errors.phone.message}</p>
              )}
            </div>
            <div>
              <textarea
                id="message"
                name="message"
                placeholder="ENTER YOUR MESSAGE"
                ref={register}
              />
            </div>
            <button type="submit" disabled={isSubmitting}>
              {isSubmitting ? "Submitting..." : "Submit"}
            </button>
          </NetlifyFormComponent>
        </NetlifyFormProvider>
      )}
    </FormContainer>
  )
}

export default Form

programmatically reset form

I need to reset my netlify form after hitting submit (reset button isn't going to hack it). Would be nice if the NetiflyForms component could return a little more manual control as an option.

Inject 'id' props to the form

Is it possible to pass the id props to the rendered form? I've tried adding a line id: form_id in my settings for the function but see no id in the DOM

React 17 support

--legacy-peer-deps seems to be fine for now..

npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^17.0.2" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.0" from [email protected]
npm ERR! node_modules/react-netlify-forms
npm ERR!   react-netlify-forms@"^1.3.1" from the root project

Does not detect form fields

Hello, I am trying to use your package however when I build my website with Netlify, it only detects one "field":

Detected form fields:
7:45:25 PM:  - bot-field

And I don't understand what is wrong with my code. I am building a form using Netlify, Formik on a Docusaurus built website.

import React, { useReducer } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import { Grid } from '@material-ui/core';
import { NetlifyForm, Honeypot } from 'react-netlify-forms'
import { useState } from "react"
import { useNetlifyForm, NetlifyFormProvider, NetlifyFormComponent} from "react-netlify-forms"
import { useFormik } from 'formik'
import {Field} from "formik";


import "./styles.module.css";

const useStyles = makeStyles(theme => ({
    input: { 
        minHeight: 100,
    },
  }));

const Commentbox = () => {
    const classes = useStyles();
    const netlify = useNetlifyForm({
      name: 'approved-comments',
      honeypotName: 'bot-field',
      onSuccess: (response, context) => {
        console.log('Successfully sent form data to Netlify Server')
      }
    })
    const {
      handleSubmit,
      handleChange,
      handleBlur,
      touched,
      errors,
      values
    } = useFormik({
      initialValues: { name: '', email: '', commentaire: '' },
      onSubmit: (values, {setStatus, resetForm}) => {
          netlify.handleSubmit(null, values);
          resetForm();
          setStatus({success: true});
  },
      validate: (values) => {
        const errors = {}
        if (
          !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)
        ) {
          errors.email = 'Adresse email invalide'
        }
        return errors
      }
    })

    return (
    <NetlifyFormProvider {...netlify}>
        <h3>Laissez un commentaire 😃</h3>
        <NetlifyFormComponent onSubmit={handleSubmit}>
          <Honeypot />
          {netlify.success && (
            <p sx={{ variant: 'alerts.success', p: 3 }}>
              Merci d'avoir commenté 😃
            </p>
          )}
          {netlify.error && (
            <p sx={{ variant: 'alerts.muted', p: 3 }}>
              Désolé, votre commentaire n'a pas pu être enregistré 😢.
            </p>
          )}
          <input type="hidden" name="form-name" value="approved-comments" />
         <TextField
          required
          id="name"
          label="Nom"
          variant="outlined"
          fullWidth
          margin="normal"
           onChange={handleChange}
           onBlur={handleBlur}
          error={errors.name}
          value={values.name}
          style = {{width: "70%"}}
        />
        <TextField
          required
          id="email"
          label="Email"
          variant="outlined"
          fullWidth
          margin="normal"
           onChange={handleChange}
           onBlur={handleBlur}
           error={errors.email}
           value={values.email}
          style = {{width: "70%"}}         
        /> 
         <TextField
          id="commentaire"
          label="Commentaire"
          variant="outlined"
          fullWidth
          margin="normal"
          multiline
           onChange={handleChange}
           onBlur={handleBlur}
          error={errors.commentaire}
           value={values.commentaire}
          inputProps={{
            className: classes.input
          }}
          style = {{width: "70%"}}          
        />   
        <button class="button button--lg button--primary" type="submit">
                Publiez votre commentaire
        </button> 
        

        </NetlifyFormComponent>
      </NetlifyFormProvider>
    )
    
  }

export default Commentbox;

Is it because I am using Material UI that it is not detecting the fields ?

Because when I try to submit the form, I only receive blank submissions :/

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.