2024-06-01 15:47:53 +03:00
|
|
|
'use client';
|
|
|
|
import { useState } from "react";
|
|
|
|
|
2024-06-01 17:40:01 +03:00
|
|
|
export enum FieldType {
|
|
|
|
number = 'number',
|
|
|
|
text = 'text'
|
|
|
|
}
|
2024-06-01 15:47:53 +03:00
|
|
|
|
2024-06-01 17:40:01 +03:00
|
|
|
export type FormFields = {
|
|
|
|
type: FieldType,
|
|
|
|
name: string,
|
|
|
|
label: string,
|
|
|
|
required: boolean
|
|
|
|
}
|
2024-06-01 15:47:53 +03:00
|
|
|
|
2024-06-01 17:40:01 +03:00
|
|
|
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 );
|
2024-06-01 15:47:53 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
2024-06-01 17:40:01 +03:00
|
|
|
<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>
|
|
|
|
)})}
|
2024-06-01 15:47:53 +03:00
|
|
|
<button type="submit">Submit</button>
|
|
|
|
</form>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
export default Form;
|
|
|
|
|