Written by: Geoffrey Callaghan
How To Create A Contact Form With React Hook Form
How To Create A Contact Form With React Hook Form
To use react-hook-form
with FabForm.io in a React application, you can follow these steps:
Install Dependencies:
react-hook-form
and axios
(for making HTTP requests) using the following commands:npm install react-hook-form axios
Create a React Component:
ContactForm.js
:import React from 'react';
import { useForm } from 'react-hook-form';
import axios from 'axios';
const ContactForm = () => {
const { register, handleSubmit, errors } = useForm();
const onSubmit = async (data) => {
try {
await axios.post('https://fabform.io/f/YOUR_FORM_ENDPOINT', data);
// Replace 'YOUR_FORM_ENDPOINT' with the actual endpoint provided by FabForm.io
console.log('Form submitted successfully');
} catch (error) {
console.error('Error submitting form:', error);
}
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
name="name"
ref={register({ required: 'Name is required' })}
/>
{errors.name && <p>{errors.name.message}</p>}
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
name="email"
ref={register({ required: 'Email is required', pattern: /^\S+@\S+$/i })}
/>
{errors.email && <p>{errors.email.message}</p>}
<label htmlFor="message">Message:</label>
<textarea
id="message"
name="message"
ref={register({ required: 'Message is required' })}
/>
{errors.message && <p>{errors.message.message}</p>}
<button type="submit">Submit</button>
</form>
);
};
export default ContactForm;
Make sure to replace 'https://fabform.io/f/YOUR_FORM_ENDPOINT'
with the actual endpoint provided by FabForm.io.
Use the Form Component:
ContactForm
component in your main application file.import React from 'react';
import ContactForm from './ContactForm';
const App = () => {
return (
<div>
<h1>Contact Us</h1>
<ContactForm />
</div>
);
};
export default App;
Style the Form (Optional):
This example uses react-hook-form
for form management, and the form data is sent to FabForm.io when the form is submitted. Adjust the validation rules and form structure based on your specific requirements. Additionally, consider implementing additional features like form validation, error handling, and feedback messages to enhance the user experience.