next-app/app/components/form.tsx
Alex Stan 43db39291e added a dynamic category page
Signed-off-by: Alex Stan <alex.stan.2010@proton.me>
2024-06-01 17:40:03 +03:00

53 lines
1.1 KiB
TypeScript

'use client';
import { useState } from "react";
export enum FieldType {
number = 'number',
text = 'text'
}
export type FormFields = {
type: FieldType,
name: string,
label: string,
required: boolean
}
const Form = <T,>({ fields, onSubmit }) => {
const [formData, setFormData] = useState({});
const handleChange = (event) => {
const { name, value } = event.target;
setFormData( (prevData) => ({
...prevData,
[name]: value
}));
}
const handleSubmit = (event) => {
event.preventDefault();
onSubmit( formData );
}
return (
<form onSubmit={handleSubmit}>
{fields.map( (field) => {
return (
<div key={field.name}>
<label>{field.label}</label>
<input
type={field.type}
name={field.name}
value={formData[field.name] || ''}
onChange={handleChange}
required={field.required}
/>
</div>
)})}
<button type="submit">Submit</button>
</form>
);
}
export default Form;