next-app/app/components/form.tsx

54 lines
1.1 KiB
TypeScript
Raw Normal View History

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