-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormModal.js
More file actions
63 lines (57 loc) · 2.09 KB
/
FormModal.js
File metadata and controls
63 lines (57 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"use client";
import { Modal, ModalOverlay, ModalContent, ModalHeader, ModalBody, ModalFooter, Button, FormControl, FormLabel, Input, useToast } from '@chakra-ui/react';
import { useState } from 'react';
const FormModal = ({ isOpen, onClose, title, fields, formData, setFormData, onSubmit, onUpdate }) => {
const toast = useToast();
const [errors, setErrors] = useState({});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({ ...prev, [name]: value }));
// Validação básica
if (!value) setErrors(prev => ({ ...prev, [name]: 'Campo obrigatório' }));
else setErrors(prev => ({ ...prev, [name]: '' }));
};
const handleSubmit = () => {
const newErrors = {};
fields.forEach(field => {
if (!formData[field.name]) newErrors[field.name] = 'Campo obrigatório';
});
if (Object.keys(newErrors).length > 0) {
setErrors(newErrors);
return;
}
if (formData.id) onUpdate(formData.id);
else onSubmit();
onClose();
};
return (
<Modal isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent>
<ModalHeader>{title}</ModalHeader>
<ModalBody>
{fields.map((field, index) => (
<FormControl key={index} isInvalid={errors[field.name]}>
<FormLabel>{field.label}</FormLabel>
<Input
type={field.type}
name={field.name}
value={formData[field.name] || ''}
onChange={handleChange}
placeholder={`Digite o ${field.label.toLowerCase()}`}
/>
{errors[field.name] && <Text color="red.500" fontSize="sm">{errors[field.name]}</Text>}
</FormControl>
))}
</ModalBody>
<ModalFooter>
<Button colorScheme="blue" mr={3} onClick={handleSubmit}>
Salvar
</Button>
<Button variant="ghost" onClick={onClose}>Cancelar</Button>
</ModalFooter>
</ModalContent>
</Modal>
);
};
export default FormModal;