I have a Gatsby/React build with a form connected to Netlify in a functional component, all working fine and outputting the submissions to the Netlify CP.
I’ve now added validation using react-hook-form and so want to preventDefault on submission to run the validator function and then submit upon successful validation.
The validation works fine, however I’m stuck trying to send the data via a function after the validation. I’ve attempted e.target.submit() but to no success.
Any ideas where I’m going wrong here and how to pass the data to netlify within a function
import React, { useEffect } from "react"
import useForm from 'react-hook-form'
import ReCAPTCHA from "react-google-recaptcha"
import { useSpring, animated } from 'react-spring'
import "../../styles/inline/themes.scss"
import styles from "./style.module.scss"
const FormBlock = ( props ) => {
const [fade, setFade] = useSpring(() => ({opacity: 0}))
useEffect(() => {
setFade({ opacity: 1, config: { duration: 900 }, delay: 100 })
})
const { register, handleSubmit, errors } = useForm()
const onSubmit = (data, e) => {
console.log(JSON.stringify(data))
e.target.submit()
}
return (
<section className={ styles.block }>
<animated.div className={ `${ styles.overlay } background--${ props.bgColour }`} style={fade}>
<div className={ styles.content }>
{ props.title &&
React.createElement(
props.titleTag,
{
className: styles.title,
},
props.title,
)
}
{ props.text &&
<p className={ props.columns } dangerouslySetInnerHTML={{ __html: props.text }}></p>
}
<form
name="contact"
method="post"
action="/contact/thanks"
data-netlify="true"
data-netlify-recaptcha="true"
data-netlify-honeypot="bot-field"
onSubmit={handleSubmit(onSubmit)}>
<div className={ styles.field }>
<label>
<p>Full name*</p>
<input type="text" name="name" ref={register({ required: true })} />
</label>
{errors.name && <span>This field is required</span>}
</div>
<div className={ styles.field }>
<label>
<p>Email address*</p>
<input type="email" name="email" ref={register({ required: true })} />
</label>
{errors.email && <span>This field is required</span>}
</div>
<div className={ styles.field }>
<label>
<p>Email address*</p>
<textarea name="message" ref={register({ required: true })} />
</label>
{errors.message && <span>This field is required</span>}
</div>
<ReCAPTCHA
className={ styles.recaptcha }
sitekey="/*remove for question*/"/>
<button className={ styles.button } type="submit">Send</button>
</form>
</div>
</animated.div>
</section>
)
}
export default FormBlock