This is a follow up question to this question:
I am using React > 16.8 with function components and hooks.
I got a parent component which manages a component to display items and add a new item. The list of items is at the parent component. The way the items are added are by a "+" button which opens a new modal window (which is a component of its own), and inside there's a form that the user can insert the details of the new items.
const registerFormRef = useRef();
<Modal
isOpen={isFormOpen}
onCancel={() => setIsFormOpen(false)}
onSubmit={() => { registerFormRef.current.onSubmitForm(); setIsFormOpen(false) }}
titleText="Register Tenant">
<AddItem onAddItem={AddNewItem} ref={registerFormRef}></RegisterTenant>
</Modal>
The AddNewItem
is a callback which adds the new item to the list. The modal has an "OK" button which serves as a submit button. It belongs to the parent modal component, not the AddItem
child.
The method in the child component:
useImperativeHandle(ref, () => (
{
onSubmitForm()
{
setIsLoading(true);
const newItem = {
name: formSettings["name"].value,
description: formSettings["description"].value,
area: "",
category: ""
}
props.onAddItem(newItem);
setIsLoading(false);
}
}));
I had an issue of getting the information from the child component which holds the form to the parent component, since the submit button as I said, belongs to the modal, I had to somehow call the callback from inside the child form. I have used the accepted answer in the linked question above. It works, but the comment says it's not a good practice passing information like that. Is there another way of passing the information from the child form to the parent component?