I have a form component that displays all the contacts in a stateful array as checkbox options. when the associated checkbox is checked, the contact should be passed into newGroup.groupContacts, and likewise should be removed if unchecked. What would the syntax be for including performing this action within handleCheckbox?
const CreateGroupForm = props => {
const defaultForm = { id: null, groupName: '', groupContacts: [] }
const [newGroup, setNewGroup] = useState(defaultForm)
const handleInputChange = event => {
const { name, value } = event.target
setNewGroup({ ...newGroup, [name]: value })
}
const handleCheckbox = event => {
console.log('called')
const {value} = event.target
console.log(event.target)
setNewGroup({...newGroup, groupContacts: [...newGroup.groupContacts, value] })
}
const handleSubmit = event => {
event.preventDefault()
if (!newGroup.groupName || !newGroup.groupContacts) return
props.addGroup(newGroup)
setNewGroup(defaultForm)
}
return (
<div>
<h2>Create a Group</h2>
<Form onSubmit={handleSubmit}>
<Form.Group >
<Form.Label>Group Name</Form.Label>
<Form.Control
type="text"
name="firstName"
onChange={handleInputChange}
placeholder="First Name"
value={newGroup.name}
/>
</Form.Group>
<Form.Group >
{props.contacts.map(contact => (
<div className="mb-3" key={contact.id}>
<Form.Check
onChange={handleCheckbox}
type='checkbox'
label={`${contact.firstName} ${contact.lastName}`}
value={contact}
/>
</div>
))}
</Form.Group>
<Button type="submit">Submit</Button>
<Button>Cancel</Button>
</Form>
</div>
)
}
export default CreateGroupForm
Aucun commentaire:
Enregistrer un commentaire