- Forums
- react
- React Form Fields Generators Using useState Object Array With Update Values
This Page Contains information about React Form Fields Generators Using useState Object Array With Update Values By jj in category react with 0 Replies. [5174], Last Updated: Mon Jun 24, 2024
jj
Sun Jul 16, 2023
0 Comments
329 Visits
You will need these 4 steps.
Example github app: React-Laravel-API-SSL-AuthenticationV2
1. Import useState
import { useState } from "react";
2. Define and initialize the form fields:
const [formFields, setFormFields] = useState([
// { type: "div", title: "divider", name: "divider", value: "Sender's Information" },
{ type: "text", title: "Your Name", name: "name", value: "Edwin" },
{ type: "password", title: "Password", name: "password", value: "", }, //onChange: 'handleAction'
{ type: "password", title: "Re-Enter Password", name: "repassword", value: "" },
]);
3. Create a variable to update each field on change
const updateState = (index, property, value) => {
setFormFields(
formFields.map((item, i) =>
i === index ? { ...item, [property]: value } : item
)
);
};
4. JSX Code:
return (
<div className="card form-signin mt-5">
<h3 className="card-header text-center bg-primary text-white">Sign Up!</h3 >
<div className="card-body">
<form className=" g-3" onSubmit={onSubmit}>
{errors &&
<div className="alert">
{Object.keys(errors).map(key => (
<p key={key}>{errors[key][0]}</p>
))}
</div>
}
{formFields.map((field, index) => {
return (
<div className="form-group" key={index}>
{field.name == 'divider' ? <hr /> : <>
<label htmlFor="form.Name">{field.title}</label>
<input
type={field.type}
className="form-control"
required
value={field.value}
name={field.name}
label={field.title}
placeholder={`Enter ${field.title}`}
onChange={(e) => {
updateState(index, 'value', e.target.value);
if (typeof field.onChange !== "undefined") {
console.log(`LINE 153 field.onChange =`, field.onChange);
window[field.onChange];
}
}}
/>
</>
}
</div>
)
})}
<div className="checkbox my-3">
<label>
<input type="checkbox" value="remember-me" /> Remember me
</label>
</div>
<button className="my-3 btn btn-lg btn-primary btn-block" type="submit">Sing Up</button>
<p className="message">Already registered? <Link to="/login">Sign In</Link></p>
</form>
</div>
</div>
)
5. Handle OnSubmit Form Values to pass to API/Axios
const onSubmit = ev => {
ev.preventDefault();
const postData = {
// Pass addional values not in the form
EXAMPLE: EXAMPLE_VALUE,
}
//https://stackoverflow.com/questions/61209803/how-to-define-a-type-under-foreach-in-typescript
formFields.forEach((field) => {
postData[field.name] = field.value;
});
axiosClient.post('/signup', postData)
.then(({ data }) => {
setUser(data.user)
setToken(data.token);
})
.catch(err => {
const response = err.response;
if (response && response.status === 422) {
setErrors(response.data.errors)
}
})
}