I'm implementing a form using React hooks instead of classes and states. This is my form:
const { values, handleChange, handleSubmit } = useForm();
const [gender, setGender] = useState("");
return (
<>
<ul className="collapsible">
<li>
<div className="collapsible-header">Step 1: Your details</div>
<div className="collapsible-body">
<div>
<label>First name</label>
<input className="browser-default" type="text" name="name" value={values.name} onChange={handleChange}/>
</div>
<div><label>Last name</label>
<input className="browser-default" type="text" name="lastName" value={values.lastName} onChange={handleChange}/> </div>
<div><label>Email</label>
<input className="browser-default" type="text" name="email" value={values.email} onChange={handleChange}/>
</div>
<button type="submit" className="browser-default">Next></button>
</div>
this is my custom hook component useForm:
import { useState } from 'react';
const useForm = (callback) => {
const [values, setValues] = useState({});
const handleSubmit = (event) => {
if (event) event.preventDefault();
callback();
};
const handleChange = (event) => {
event.persist();
setValues(values => ({ ...values, [event.target.name]: event.target.value }));
};
return {
handleChange,
handleSubmit,
values,
}
};
export default useForm;
now I would like to create an Object with the data of the submitted form to post with Axios on a server. The object should be like this:
let data ={
firstName: name,
lastName: lastName,
email:email,
number:number,
gender:gender,
dob: `${day}-${month}-${year}`,
comments: comments
}
considered that with the custom Hook I've created basically only one state "values", how can i assign the respective value to each property? For example " firstName: [event.target.name] " would work? Thank you guys!