react-netlify-forms

Contact form with invisible reCAPTCHA

First, import required components in your class or function:

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

Also make sure to set the following environment variables for Netlify:

  • SITE_RECAPTCHA_KEY
    (used by Netlify)
  • SITE_RECAPTCHA_SECRET
    (used by Netlify)

Additionally, you need to make sure to pass

SITE_RECAPTCHA_KEY
as a prop to the reCAPTCHA-component.

This example is served by Gatsby and uses an additional variable called GATSBY_SITE_RECAPTCHA_KEY for that.

Then, you can use the

NetlifyForm
component in place of the standard form tag. It will provide you form handlers, which manage submitting data to Netlify. Play around and modify this interactive example (
sx
is used for styling):

<NetlifyForm
name='reCAPTCHA'
action='/thanks'
honeypotName='bot-field'
enableRecaptcha
onSuccess={(response, context) => {
console.log('Successfully sent form data to Netlify Server')
context.formRef.current.reset()
}}
>
{({ handleChange, success, error }) => (
<>
<Honeypot />
<Recaptcha siteKey={GATSBY_SITE_RECAPTCHA_KEY} invisible />
{success && (
<p sx={{ variant: 'alerts.success', p: 3 }}>
Thanks for contacting us!
</p>
)}
{error && (
<p sx={{ variant: 'alerts.muted', p: 3 }}>
Sorry, we could not reach servers. Because it only works on Netlify,
our GitHub demo does not provide a response.
</p>
)}
<div>
<label htmlFor='name' sx={{ variant: 'forms.label' }}>
Name:
</label>
<input
type='text'
name='name'
id='name'
onChange={handleChange}
sx={{ variant: 'forms.input' }}
/>
</div>
<div sx={{ pt: 2 }}>
<label htmlFor='message' sx={{ variant: 'forms.label' }}>
Message:
</label>
<textarea
type='text'
name='message'
id='message'
rows='4'
onChange={handleChange}
sx={{ variant: 'forms.textarea' }}
/>
</div>
<div sx={{ pt: 3 }}>
<button type='submit' sx={{ variant: 'buttons.success' }}>
Submit
</button>
<button type='reset' sx={{ variant: 'buttons.danger' }}>
Reset
</button>
</div>
</>
)}
</NetlifyForm>
© 2023 Björn Clees, made with ❤ using Gatsby