Reputation: 101
I want to use react-hook-form
to handle input from the user. React gives me an error saying "handleSubmit is not a function". Any help would be appreciated.
My code is as followed (react-hook-form 7.13.0)
import { useForm } from "react-hook-form";
import axios from "axios";
import styled from "styled-components";
const Style = styled.div`
.form {
width: 200px;
display: flex;
flex-direction: column;
}
`;
const Add = (props) => {
const { register , handleSubmit } = useForm();
const onSubmit = (e, data) => {
e.preventDefault();
console.log(data);
addReview(data);
}
const addReview = (data) => {
axios.POST("http://localhost:3000/reviews", data).then(() => {
props.setReviews([...props.reviews, {data}])
})
}
return (
<Style>
<h3>Add a review</h3>
<form className="form" onSubmit={handleSubmit(onSubmit)}>
<input type="text" placeholder="Book Title" ref={register}></input>
<input type="text" placeholder="Rating" ref={register}></input>
<input type="text" placeholder="Review" ref={register}></input>
<input type="submit" placeholder="Review"></input>
</form>
</Style>
)
};
export default Add;
Upvotes: 5
Views: 10376
Reputation: 77
You have to register your input into the hook by invoking the "register" function
Like this <input type="text" placeholder="Rating" {...register("Rating")}></input>
Upvotes: -1
Reputation: 28414
Pass this for every input
with the name
in order to register:
{...register("rating")}
Reference: https://react-hook-form.com/api/useform/register
Upvotes: 4
Reputation: 89
Can you please try this...
const Add = (props) => {
const { register, handleSubmit } = useForm();
const onSubmit = (data) => {
console.log(data);
addReview(data);
};
const addReview = (data) => {
axios.POST("http://localhost:3000/reviews", data).then(() => {
props.setReviews([...props.reviews, { data }]);
});
};
return (
<Style>
<h3>Add a review</h3>
<form className="form" onSubmit={handleSubmit(onSubmit)}>
<input
type="text"
placeholder="Book Title"
{...register("bookTitle")}
></input>
<input type="text" placeholder="Rating" {...register("rating")}></input>
<input type="text" placeholder="Review" {...register("review")}></input>
<input type="submit" placeholder="Review"></input>
</form>
</Style>
);
};
Upvotes: 2
Reputation: 2058
You have a typo.
This is what you have currently:
<form className="form" onSubmit={handleSubmit(onSubmit)}>
You call handleSubmit(onSubmit)
but I'm guessing you are trying to use onSubmit
as a handler. Replace the line above with this:
<form className="form" onSubmit={onSubmit}>
Upvotes: -1