React Firebase is not getting data from React Hook form - reactjs

This is what I'm stuck with for last couple of hours. I have tried default values from react hook form. I kinda getting the user input on the console but for firebase it's showing error. It is working with the normal input system
import React, { useEffect } from "react";
import {
useAuthState,
useCreateUserWithEmailAndPassword,
} from "react-firebase-hooks/auth";
import { useForm } from "react-hook-form";
import { Link, useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import auth from "../../firebase.init";
import Loading from "../Shared/Loading";
import GoogleLogin from "./GoogleLogin";
const Signup = () => {
const [createUserWithEmailAndPassword,loading] =
useCreateUserWithEmailAndPassword(auth);
const navigate = useNavigate();
const [user] = useAuthState(auth);
useEffect(() => {
if (user) {
navigate("/home");
}
}, [navigate, user]);
const {
register,
formState: { errors },
handleSubmit,
} = useForm();
const onSubmit = (data) => {
createUserWithEmailAndPassword(data);
if (user) {
toast.success("Successfully Registered");
}
console.log(data);
};
if(loading){
return <Loading></Loading>
}
return (
<section className="container mx-auto px-5 gap-5 md:px-12">
<form className="py-5 card" onSubmit={handleSubmit(onSubmit)}>
<div className="mt-5 mb-5">
<input
type="text"
className="input input-bordered py-5"
placeholder="Your Full Name"
{...register("name", {
required: { value: true, message: "Name is required" },
maxLength: 80,
pattern: {
value: /^[\w'\-,.][^0-9_!¡?÷?¿/\\+=##$%ˆ&*(){}|~<>;:[\]]{2,}$/,
message: `Don't use special characters`,
},
})}
/>
<br />
</div>
<div className="form-control w-full max-w-xs">
<label className="label">
<span className="label-text">Email</span>
</label>
<input
type="email"
placeholder="Your Email"
className="input input-bordered w-full max-w-xs"
{...register("email", {
required: {
value: true,
message: "Email is Required",
},
pattern: {
value: /[a-z0-9]+#[a-z]+\.[a-z]{2,3}/,
message: "Provide a valid Email",
},
})}
/>
<label className="label">
{errors.email?.type === "required" && (
<span className="label-text-alt text-red-500">
{errors.email.message}
</span>
)}
{errors.email?.type === "pattern" && (
<span className="label-text-alt text-red-500">
{errors.email.message}
</span>
)}
</label>
</div>
<div>
<input
type="password"
placeholder="Password"
className="input input-bordered"
{...register("password", {
required: {
value: true,
message: `Please provide a password between 6 to 30 character`,
},
})}
/>
<label className="label">
{errors.password?.type === "required" && (
<span className="label-text-alt text-red-500">
{errors.password.message}
</span>
)}
{errors.password?.type === "pattern" && (
<span className="label-text-alt text-red-500">
{errors.password.message}
</span>
)}
</label>
</div>
<input className="btn btn-primary" value="Register" type="submit" />
</form>
<GoogleLogin></GoogleLogin>
<div>
<Link className="btn btn-se" to="/login">
Login
</Link>
</div>
</section>
);
};
export default Signup;
So after submitting, I can see the data on console but can't send them to firebase.

Related

React Hook form and yup validation

I have created a buy now component for my react js ecommerce website. The problem I am facing is that the validation of form is not being done. I have used a resolver but still it doesnot validate my form.Here is my code :`
import React, { useEffect, useState } from 'react'
import "./e.css"
import { useForm } from "react-hook-form";
import { yupResolver } from "#hookform/resolvers/yup"
import * as yup from "yup"
export default function BuyNow(props) {
const [country, setCountry] = useState([])
useEffect(() => {
const getcountry = async () => {
const res = await fetch("http://localhost:3000/setpk.json")
const getcon = await res.json()
setCountry(await getcon)
}
getcountry()
}, [])
const schema = yup.object({
fullname: yup.string().required(),
email: yup.string().email().required(),
address: yup.string().required(),
phoneno: yup.number().required().integer().min(11),
city: yup.string().required(),
payment: yup.string().required()
})
const { register, handleSubmit, watch, formState: { errors } } = useForm({
resolver: yupResolver(schema)
});
const onSubmit = (data) => {
console.log(data)
}
return (
<>
<div className="details h-[90vh] bg-indigo-600 mt-20 text-indigo-400 text-center">
<h1 className='text-indigo-200'>Buy Now</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<div className='space-y-5 mt-4 flex flex-col w-[70%] sm:w-[66%] md:w-[55%] mx-auto'>
<input name="thename" id="name" placeholder='Name' {...register("fullname")
} />
<input name="email" id="email" placeholder='Email' className="text-indigo-400 "
{...register("email")
} />
<input name="address" id="address" placeholder='Shipping Address' {...register("address")
} />
<input type="number" name="phone" id="" placeholder='Phone No.' {...register("phoneno")
} />
<select name="sa" id="as" {...register("city")
} >
<option disabled selected >--City Name--</option>
{
country.map((countryget, i) => (
<option key={i} >{countryget.city}</option>
))
}
</select>
<div className='flex relative w-auto'>
<select name="" id="" className='thepayment basis-full w-[70%] ' {...register("payment")
}>
<option disabled selected > --Payment Method-- </option>
<option >Credit Card</option>
<option >Cash on delivery</option>
<option >Bank Transfer</option>
</select>
<img src="http://localhost:3000/creditcard.png" alt="" className='absolute w-10 right-5' />
</div>
{/* <button type="submit" className='bg-indigo-600 p-2 rounded-lg font-mono absolute '>Proceed ➔</button> */}
</div>
<input type="submit" className='bg-rose-600 p-2 rounded-lg font-mono text-white mt-3' />
</form>
</div>
<div className="pricesection h-20 bg-rose-600 fixed bottom-0 left-0 right-0 flex items-center px-1 text-rose-100 justify-evenly md:justify-around">
<h2 className='text-xl md:text-2xl md:font-bold '>Total Price</h2>
<h2 className='text-2xl font-bold '>${props.totalprice}</h2>
</div>
</>
)
}
I want the form to be uncontrolled.I have written schema and also used resolver.
I fixed this by putting yup.string() instead of yup.integer()
phoneno: yup.number().required().integer().min(11),

How prevent submit edit form when anything is not changed?

I have a form like this that I created with context crud project. Here I want that if no changes have been made in the form, it should not be updated and a notification should be issued. How can I do this?
Note: also, if any input is empty, do not submit. How can I do this without required the input. How can I fix these problems?
import React from "react";
import { NavLink } from "react-router-dom";
import { useContext, useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { GlobalContext } from "../../context/GlobalState";
import styles from "../ContactForm/Form.module.scss";
import { toast } from "react-toastify";
const EditContactForm = () => {
const { contacts, UPDATE_CONTACT } = useContext(GlobalContext);
const [selectedContact, setSelectedContact] = useState({
id: "",
name: "",
surname: "",
fatherName: "",
specialty: "",
email: "",
gender: "",
test:''
});
const history = useNavigate();
const { id } = useParams();
useEffect(() => {
const userId = id;
const selectedContact = contacts.find((user) => String(user.id) === userId);
if (selectedContact) {
setSelectedContact(selectedContact);
}
}, [id, contacts]);
function onSubmit(e) {
e.preventDefault();
if(selectedContact){
UPDATE_CONTACT(selectedContact);
console.log("new user edited:", selectedContact);
history("/contacts");
toast('updated')
}
else if(selectedContact===contacts){
toast('anything doesnt changed') // problem is there
}
}
const handleOnChange = (e) => {
setSelectedContact((selectedContact) => ({
...selectedContact,
[e.target.name]: e.target.value,
}));
};
const inputHandleChange = (e) => {
setSelectedContact({
...selectedContact,
[e.target.name]: e.target.checked ? e.target.id : "",
});
};
const selectOptions = [
{ label: "One", value: 1 },
{ label: "Two", value: 2 },
{ label: "Three", value: 3 },
];
const onChange = (e) => setSelectedContact({ ...selectedContact, [e.target.name]: e.target.value })
return (
<div className={styles.form}>
<form onSubmit={onSubmit}>
<div class="mb-3 row row d-flex justify-content-around">
<label className={`col-sm-2 p-0 ${styles.inputLabel}`}>Name</label>
<div class="col-sm-8">
<input
class="form-control"
name="name"
required
value={selectedContact?.name ?? ""}
onChange={handleOnChange}
/>
</div>
</div>
<div class="mb-3 row row d-flex justify-content-around">
<label className={`col-sm-2 p-0 ${styles.inputLabel}`}>Surname</label>
<div class="col-sm-8">
<input
class="form-control"
name="surname"
required
value={selectedContact?.surname ?? ""}
onChange={handleOnChange}
/>
</div>
</div>
<div class="mb-3 row row d-flex justify-content-around">
<label className={`col-sm-2 p-0 ${styles.inputLabel}`}>
Father Name
</label>
<div class="col-sm-8">
<input
class="form-control"
name="fatherName"
required
value={selectedContact?.fatherName ?? ""}
onChange={handleOnChange}
/>
</div>
</div>
<div class="mb-3 row row d-flex justify-content-around">
<label className={`col-sm-2 p-0 ${styles.inputLabel}`}>Email</label>
<div class="col-sm-8">
<input
class="form-control"
name="email"
required
value={selectedContact?.email ?? ""}
onChange={handleOnChange}
/>
</div>
</div>
<div class="mb-3 row row d-flex justify-content-around">
<label className={`col-sm-2 p-0 ${styles.inputLabel}`}>
Specialty
</label>
<div class="col-sm-8">
<input
class="form-control"
name="specialty"
required
value={selectedContact?.specialty ?? ""}
onChange={handleOnChange}
/>
</div>
</div>
<div className="mb-3 row row d-flex justify-content-around">
<label className={`col-sm-2 p-0 ${styles.inputLabel}`}>position</label>
<div className="col-sm-8 d-flex justify-content-center align-items-center">
<select
onChange={onChange}
value={selectedContact.test}
name="test"
class="form-select"
aria-label="Default select example"
>
{selectOptions.map((item) => (
<option
key={item.value}
value={item.value}
>
{item.label}
</option>
))}
</select>
</div>
</div>
<div className="mb-3 row row d-flex justify-content-around">
<label className={`col-sm-2 p-0 ${styles.inputLabel}`}>Gender</label>
<div className="col-sm-8">
<div class="form-check form-check-inline ">
<input
class="form-check-input"
type="radio"
name="gender"
id="male"
checked={selectedContact.gender === "male"}
onChange={inputHandleChange}
/>
<label class="form-check-label">Male</label>
</div>
<div class="form-check form-check-inline">
<input
class="form-check-input"
type="radio"
name="gender"
id="female"
checked={selectedContact.gender === "female"}
onChange={inputHandleChange}
/>
<label class="form-check-label">Female</label>
</div>
</div>
</div>
<div className="mb-3 row d-flex justify-content-around">
<div class="form-check col-sm-11">
<input
class="form-check-input"
type="checkbox"
name="updatesNotification"
id="update"
checked={selectedContact.updatesNotification === "update"}
onChange={(e) =>
setSelectedContact({
...selectedContact,
[e.target.name]: e.target.checked ? e.target.id : "",
})
}
/>
<label class="form-check-label" for="flexCheckDefault">
I want to be notified of updates
</label>
</div>
</div>
<div className={styles.buttons}>
<button type="submit" class="btn btn-primary">
Update a contact
</button>
<NavLink to="/contacts" className="btn btn-danger m-2">
Cancel
</NavLink>
</div>
</form>
</div>
);
};
export default EditContactForm;
import React, { useState } from "react";
import { useContext } from "react";
import { GlobalContext } from "../../context/GlobalState";
import { useNavigate } from "react-router-dom";
import { NavLink } from "react-router-dom";
import { v4 as uuidv4 } from "uuid";
import styles from "../ContactForm/Form.module.scss";
import { toast } from "react-toastify";
import { Checkbox, Button, Form, Input, Select, Radio } from "antd";
const Form1 = () => {
const { ADD_CONTACT } = useContext(GlobalContext);
const [contact, setContact] = useState({
id: uuidv4(),
name: "",
surname: "",
fatherName: "",
specialty: "",
email: "",
gender: "",
updatesNotification: "",
test: "",
});
const { Option } = Select;
const { name, surname, fatherName, specialty, email } = contact;
let history = useNavigate();
const onSubmit = () => {
if (contact) {
ADD_CONTACT(contact);
history("/contacts");
console.log(contact);
toast.success("Contact successfully added");
}
else{
???
}
};
const selectOptions = [
{ label: "One", value: 1 },
{ label: "Two", value: 2 },
{ label: "Three", value: 3 },
];
return (
<>
<Form
onFinish={onSubmit}
className={styles.form}
name="myForm"
initialValues={{
remember: true,
}}
autoComplete="off"
labelCol={{
span: 2,
}}
wrapperCol={{
span: 16,
}}
>
<div className="row">
<Form.Item
label="Name"
rules={[{ required: true, message: "Please input your name!" }]}
>
<Input
placeholder="Enter Your Name"
value={name}
name="name"
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</Form.Item>
</div>
<Form.Item
label="Surname"
rules={[{ required: true, message: "Please input your surname!" }]}
>
<Input
placeholder="Enter Your Surname"
value={surname}
name="surname"
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</Form.Item>
<Form.Item
label="Father Name"
rules={[{ required: true, message: "Please input your surname!" }]}
>
<Input
placeholder="Enter Your FatherName"
value={fatherName}
name="fatherName"
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</Form.Item>
<Form.Item
label="Email"
rules={[{ required: true, message: "Please input your mail!" }]}
>
<Input
name="email"
placeholder="your mail"
value={email}
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</Form.Item>
<Form.Item
label="Specialty"
rules={[{ required: true, message: "Please input your specialty!" }]}
>
<Input
name="specialty"
placeholder="your specialt"
value={specialty}
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</Form.Item>
<Form.Item label='Category'>
<Select
onChange={(e)=>setContact({ ...contact, test : e })}
defaultValue='category'
// value={contact.test}
name="test"
style={{
width: 120,
}}
>
{selectOptions.map((item) => (
<Option key={item.value} value={item.value}></Option>
))}
</Select>
</Form.Item>
<Form.Item label="Gender">
<Radio.Group
onChange={(e) =>
setContact({
...contact,
[e.target.name]: e.target.checked ? e.target.id : "",
})
}
name="gender"
rules={[{ required: true, message: "Please your gender!" }]}
>
<Radio
id="female"
value="Female"
checked={contact.gender === "female"}
>
Female
</Radio>
<Radio id="male" value="Male" checked={contact.gender === "male"}>
Male
</Radio>
</Radio.Group>
</Form.Item>
<Form.Item>
<Checkbox
name="updatesNotification"
checked={contact.updatesNotification === "update"}
id="update"
onChange={(e) =>
setContact({
...contact,
[e.target.name]: e.target.checked ? e.target.id : "",
})
}
>
I want to be notified of updates
</Checkbox>
</Form.Item>
<div className={styles.buttons}>
<Button type="primary" htmlType="submit">
Add contact
</Button>
<NavLink to="/contacts">
<Button danger>Cancel</Button>
</NavLink>
</div>
</Form>
</>
);
};
export default Form1;
enter image description here
One way to check if two objects are equal is to transform them into string.
JSON.stringify(selectedContact) === JSON.stringify(contacts.find((user) => user.id === selectedContact.id))
For checking if one if the data is empty one way is using the method some, this method send true if one the item in an array match the condition.
if (Object.keys(selectedContact).some(key => !selectedContact[key])) {
alert('There are missing information')
}

Error while creating validations for react-hook-form

I am trying to create validations for my react-hook-form but when I go try to display the errors on the front end I receive this error.
×
TypeError: Cannot read properties of undefined (reading 'name')
It seems like everything is working until I try to display it with the following code
{errors.name && errors.name.message}
import emailjs from "emailjs-com";
import { useForm } from "react-hook-form";
const Contact = () => {
const [successMessage, setSuccessMessage] = useState("");
const { register, handleSubmit, errors } = useForm();
const serviceID = "s_ID";
const templateID = "t_ID";
const userID = "user_12345";
const onSubmit = (data, r) => {
sendEmail(
serviceID,
templateID,
{
name: data.name,
email: data.email,
subject: data.subject,
description: data.description,
},
userID
)
r.target.reset();
}
const sendEmail = (serviceID, templateID, variables, userID) => {
emailjs.send(serviceID, templateID, variables, userID)
.then(() => {
setSuccessMessage("Form sent successfully! I'll contact you as soon as possible");
}).catch(err => console.error(`Something went wrong ${err}`));
};
return (
<div className="contacts">
<div className="text-center">
<h1 className="bold upper-case">contact me</h1>
</div>
<div className="container">
<form onSubmit={handleSubmit(onSubmit)}>
<div className="row">
<div className="col-md-6 col-xs-12">
{/* Name Input */}
<input type="text" className="form-control" placeholder="Name" name="name"
{
...register("name", {
required: "Please enter your name",
maxLength: {
value: 20,
message: "Name must not be longer than 20 characters",
}
})
} />
<span className="error-message">
<p> {errors.name && errors.name.message} </p>
</span>
{/* Email Input */}
<input type="email" className="form-control" placeholder="E-mail" name="email" />
{/* Subject Input */}
<input type="text" className="form-control" placeholder="Subject" name="subject" />
</div>
<div className="col-md-6 col-xs-12">
{/* Subject Input */}
<textarea type="text" className="form-control" placeholder="Subject" name="description" />
<div className="text-center center">
<button className="btn btn-outline-dark contact-button p-button mt-3" type="submit">
Send!
</button>
</div>
</div>
</div>
</form>
</div >
</div >
)
}
export default Contact
Your code helped me debug my EmailJS submission so it's only right if I try my best to help you.
I'm able to successfully display my validation error messages by doing the following:
const {
register,
handleSubmit,
formState: { errors },
} = useForm<IContactForm>();
.
.
.
<form>
<input {...register("firstName", { required: "ENTER YOUR FIRST NAME" })}/>
{errors.firstName && errors.firstName.message}
</form>
Only difference I see is that you don't have 'formState: {errors}' for your useForm hook.

How to use the callback function in ReactJS Hooks

I have a form with several fields. And I am doing the validation as well.
So on the onSubmit it calls to a function handleSubmit and there I am doing the validation.
So if there are any empty fields, they will produce an error and will be shown below each field.
If there are NO errors, it will be route to the /register-success component.
Now my problem is, if there are any empty fields when I click on Register button, those respective errors are being set using setErrors. But it is not being updated to the errors variable right after it is being set.
So unlike in class components I could have used a callback function with setState but in hooks I saw a workaround to use useEffect. It is working, but now I don't know how to redirect the page to /register-success within the useEffect because I can't do it within the handleSubmit because of the errors are not getting updated even after the setErrors
So How can I do the callback operation using react hooks or how can I redirect the page within the useEffect?
Here's my code:
import React, { useState, useEffect } from "react";
import { Link, useHistory } from "react-router-dom";
function Register() {
const [values, setValues] = useState({});
const [errors, setErrors] = useState({});
const handleChange = (event) => {
event.persist();
setValues((values) => ({
...values,
[event.target.name]: event.target.value,
}));
};
useEffect(() => {
if (Object.keys(errors).length === 0) {
// RIDERECT TO THE /register-success ==============================
} else {
// alert("Errors found");
}
}, [errors]);
const validateForm = (values) => {
let allErrors = {};
if (!values.name) {
allErrors.name = "User name is required!";
}
if (!values.phonenumber) {
allErrors.phonenumber = "Phone number is required!";
}
if (!values.email) {
allErrors.email = "Email address is required!";
} else if (!/\S+#\S+\.\S+/.test(values.email)) {
allErrors.email = "Email address is invalid!";
}
if (!values.password) {
allErrors.password = "Please provide the password!";
}
if (!values.confirmpassword) {
allErrors.confirmpassword = "Please confirm the password is the same!";
}
return allErrors;
};
const handleSubmit = (event) => {
if (event) event.preventDefault();
setErrors(validateForm(values));
};
return (
<form onSubmit={handleSubmit}>
<div className="container login-container">
<div className="row">
<div className="col-md-6 login-form-2">
<h3>Register to post your ad</h3>
<div className="form-group">
<input
onChange={handleChange}
type="text"
className="form-control"
placeholder="Name *"
name="name"
value={values.name || ""}
/>
{errors.name && (
<div class="alert alert-danger" role="alert">
{errors.name}
</div>
)}
</div>
<div className="form-group">
<input
onChange={handleChange}
type="text"
name="phonenumber"
className="form-control"
placeholder="Phone Number *"
value={values.phonenumber || ""}
/>
{errors.phonenumber && (
<div class="alert alert-danger" role="alert">
{errors.phonenumber}
</div>
)}
</div>
<div className="form-group">
<input
onChange={handleChange}
type="text"
name="email"
className="form-control"
placeholder="Your Email *"
value={values.email || ""}
/>
{errors.email && (
<div class="alert alert-danger" role="alert">
{errors.email}
</div>
)}
</div>
<div className="form-group">
<input
onChange={handleChange}
type="password"
name="password"
className="form-control"
placeholder="Password *"
value={values.password || ""}
/>
{errors.password && (
<div class="alert alert-danger" role="alert">
{errors.password}
</div>
)}
</div>
<div className="form-group">
<input
onChange={handleChange}
type="password"
className="form-control"
placeholder="Confirm Password *"
name="confirmpassword"
value={values.confirmpassword || ""}
/>
{errors.confirmpassword && (
<div class="alert alert-danger" role="alert">
{errors.confirmpassword}
</div>
)}
</div>
<div className="form-group">
{/* <Link to="/register-success"> */}
<input type="submit" className="btnSubmit" value="Register" />
{/* </Link> */}
</div>
<div className="form-group btnForgetPwd">
By clicking "Register" you are agreeing to our{" "}
<Link target="_blank" to="/terms-and-conditions">
<a
style={{
color: "white",
textDecoration: "underline",
fontStyle: "italic",
}}
>
Terms and Conditions
</a>
</Link>
</div>
</div>
<div className="col-md-6 login-form-1">
<div className="login-logo">
<img src="https://image.ibb.co/n7oTvU/logo_white.png" alt="" />
</div>
{/* Register */}
<h3>Already a member? Login</h3>
<div className="form-group text-center pt-5">
<Link to="/login">
<input type="button" className="btnSubmit" value="Login" />
</Link>
</div>
</div>
</div>
</div>
</form>
);
}
export default Register;
You can do something like that :
const handleSubmit = (event) => {
if (event) event.preventDefault();
const validationErrors = validateForm(values)
if(Object.keys(validationErrors).length > 0) {
setErrors(validationErrors);
return;
}
// REDIRECT TO THE /register-success ==============================
};
If you've got errors redirection won't be triggered and component will re-render with errors updated

React, Display message after submitting form with react-hook-form

I use react-hook-form and would like to display message to the user after submitting form. I know how to do that with alert, but would like to have that message as a paragraph. After submitting fields should be again empty.
Here is my Form component:
import React from "react";
import { useForm } from "react-hook-form";
const Form = ({ title }) => {
const { register, handleSubmit, errors } = useForm();
const onSubmit = (data, e) => {
e.preventDefault();
console.log(data);
alert(`thank you ${data.name} for your message`);
};
return (
<div className="formContainer">
<Title title="Lets stay in touch" />
<div className="form">
<form onSubmit={handleSubmit(onSubmit)}>
<div className="form__row">
<input
className={`inputForm ${errors.name ? "inputFormError" : ""}`}
name="name"
type="text"
placeholder="name"
ref={register({ required: true })}
/>
<input
className={`inputForm ${
errors.surname ? "inputFormError" : ""
}`}
name="surname"
type="text"
placeholder="surname"
ref={register({ required: true })}
/>
</div>
<div>
<textarea
className={`inputForm areaForm ${
errors.message ? "inputFormError" : ""
}`}
name="message"
placeholder="Your message"
ref={register({ required: true })}
></textarea>
</div>
<div>
<button className="form__formButton" type="submit">
Send
</button>
</div>
</form>
</div>
</div>
);
};
export default Form;
Pretty simple with just a useState to show the message and reset API from hookForm to reset the form :
import React from "react";
import { useForm } from "react-hook-form";
const Form = ({ title }) => {
const [message, setMessage] = useState('');
const { register, handleSubmit, errors, reset } = useForm();
const onSubmit = (data, e) => {
e.preventDefault();
console.log(data);
setMessage(`thank you ${data.name} for your message`);
reset();
};
return (
<div className="formContainer">
<Title title="Lets stay in touch" />
<div className="form">
{message}
<form onSubmit={handleSubmit(onSubmit)}>
<div className="form__row">
<input
className={`inputForm ${errors.name ? "inputFormError" : ""}`}
name="name"
type="text"
placeholder="name"
ref={register({ required: true })}
/>
<input
className={`inputForm ${
errors.surname ? "inputFormError" : ""
}`}
name="surname"
type="text"
placeholder="surname"
ref={register({ required: true })}
/>
</div>
<div>
<textarea
className={`inputForm areaForm ${
errors.message ? "inputFormError" : ""
}`}
name="message"
placeholder="Your message"
ref={register({ required: true })}
></textarea>
</div>
<div>
<button className="form__formButton" type="submit">
Send
</button>
</div>
</form>
</div>
</div>
);
};
export default Form;

Resources