import React from 'react';
import FormField from '../ui/FormField';
import { useForm } from '../../hooks/useForm';
/**
* A form component for creating or updating a block.
*
* @param {object} props - The component's props.
* @param {object} [props.initialData] - Initial data for the form fields (e.g., when editing a block).
* @param {function} props.onSubmit - The function to call when the form is submitted and validated.
* @param {function} props.onCancel - The function to call when the cancel button is clicked.
* @param {boolean} [props.loading=false] - A boolean indicating whether the form is currently in a loading state.
* @returns {JSX.Element} The BlockForm component.
*/
const BlockForm = ({ initialData, onSubmit, onCancel, loading }) => {
const { values, errors, handleChange, handleBlur, validate } = useForm(
initialData || {
name: '',
no_of_floors: '',
description: '',
},
{
name: { required: true, minLength: 2 },
no_of_floors: { required: true },
}
);
const handleSubmit = (e) => {
e.preventDefault();
if (validate()) {
onSubmit({
...values,
no_of_floors: parseInt(values.no_of_floors, 10)
});
}
};
return (
<form onSubmit={handleSubmit} className="space-y-4">
<FormField
label="Block Name"
name="name"
value={values.name}
onChange={handleChange}
onBlur={handleBlur}
error={errors.name}
required
/>
<FormField
label="Number of Floors"
name="no_of_floors"
type="number"
value={values.no_of_floors}
onChange={handleChange}
onBlur={handleBlur}
error={errors.no_of_floors}
required
min="1"
/>
<FormField
label="Description"
name="description"
type="textarea"
value={values.description}
onChange={handleChange}
onBlur={handleBlur}
error={errors.description}
placeholder="Enter block description..."
/>
<div className="flex justify-end space-x-2 pt-4">
<button
type="button"
onClick={onCancel}
className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-200 rounded-md hover:bg-gray-300"
disabled={loading}
>
Cancel
</button>
<button
type="submit"
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 disabled:opacity-50"
disabled={loading}
>
{loading ? 'Saving...' : initialData ? 'Update' : 'Create'}
</button>
</div>
</form>
);
};
export default BlockForm;
Source