Skip to content

Contact Form

First, import required components in your class or function:

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

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='Contact'
action='/thanks'
honeypotName='bot-field'
onSuccess={(response, context) => {
console.log('Successfully sent form data to Netlify Server')
context.formRef.current.reset()
}}
>
{({ handleChange, success, error }) => (
<>
<Honeypot />
{success && (
<p>
Thanks for contacting us!
</p>
)}
{error && (
<p>
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'>
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>
<button type='reset'>
Reset
</button>
</div>
</>
)}
</NetlifyForm>

Now, that we know how to quickly build a form, let us take a closer look at how we can get control over the form. This is where context jumps in. Actually, we already used it. We consumed it as children of NetlifyForm to get access to state and form handlers. We could also use it to access formRef and manually reset the form as this example shows:

<NetlifyForm name='Contact' action='/thanks' honeypotName='bot-field'>
{({ handleChange, formRef }) => (
<div>
<input
type='text'
name='name'
id='name'
onChange={handleChange}
/>
{/* This button, for example, uses the context to access formRef and then
** programmatically reset this form. */}
<button
type='button'
onClick={() => formRef.current.reset()}
>
Custom reset button
</button>
</div>
)}
</NetlifyForm>

Same example, without destructuring, makes it clear where we access the context:

<NetlifyForm name='Contact' action='/thanks' honeypotName='bot-field'>
{(context) => (
<div>
<input
type='text'
name='name'
id='name'
onChange={context.handleChange}
/>
<button
type='button'
onClick={() => context.formRef.current.reset()}
>
Custom reset button
</button>
</div>
)}
</NetlifyForm>

Head over to the docs for a complete list of context variables.