I’m not sure why I’m getting this error. I’m new to react and I created this simple form but it’s gives error on rendering. It’s four field input form where I’m using HANDLECHANGE function on onChange of each input and getting all the values according to their name, Used handleSubmit function to avoid the normal behavior of form. handleSubmit is not the issue factor but still I tried removing it but the code still doesn’t work.Please let me know if I’m doing something stupid. Here are my files for the code.
import React from "react";
import useForm from "./useForm";
function FormSignup() {
const [values, handleChange, handleSubmit] = useForm();
return (
<div className="formContent">
<form className="form" onSubmit={handleSubmit}>
<h1>Get Started with us today!</h1>
<div className="formElements">
<label htmlFor="username" className="formLabel">
Username
</label>
<input
type="text"
name="username"
className="Inputs"
onChange={handleChange}
value={values.username}
placeholder="Enter your username"
/>
<label htmlFor="email" className="formLabel">
Email
</label>
<input
type="email"
name="email"
className="Inputs"
onChange={handleChange}
value={values.email}
placeholder="Enter your email"
/>
<label htmlFor="password" className="formLabel">
Password
</label>
<input
type="password"
name="password"
className="Inputs"
onChange={handleChange}
value={values.password}
placeholder="Enter your password"
/>
<label htmlFor="password2" className="formLabel">
Confirm Password
</label>
<input
type="password"
name="password2"
className="Inputs"
onChange={handleChange}
value={values.password2}
placeholder="Confirm your password"
/>
<button className="formButton" type="submit">
SignUp
</button>
</div>
</form>
</div>
);
}
export default FormSignup;
In my useform file I’m handling the form input with state hook. Wondering if I did something wrong here.
import { useState } from "react";
const useForm = () => {
const [values, setValues] = useState({
username: "",
email: "",
password: "",
password2: "",
});
const handleChange = (e) => {
const { name, value } = e.target;
setValues({ ...values, [name]: value });
};
function handleSubmit(e) {
e.preventdefault();
}
return {
handleChange,
values,
handleSubmit,
};
};
export default useForm;
>Solution :
You’re returning an object from your useForm hook but destructuring it as if it’s an array. I think if you change
const [values, handleChange, handleSubmit] = useForm();
to
const {values, handleChange, handleSubmit} = useForm();
your code should work.