I found the following answer to a question that I currently have (link). In in, he said "If you pass any props to the component from the parent component and you update that prop in children or that prop update in the parent component so both will re-render." Can anyone give me a brief code snippet that achieves the case where you pass a prop to a child component from a parent component, then you update it in the child component so that both components will re-render? I am not still sure if this is attainable...
(scenario) Let's say I have a parent component which is a sidebar containing a list of items. When I click an edit button of one of items, a modal (child component) where I can change the item name pops up. As hitting a submit button with a new item name as an input, the previous item name gets updated with the new one behind the scenes and the modal gets closed. As this happens, I would like the parent component to re-render to reflect the change on UI.
const Parent () => {
const [isOpen, setIsOpen] = useState(true);
const [{ items }, dipatch} = useStateValue(); //Fetch items object through React Context API
return (
{items.map((item) => (
<p>{item}<p />
))}
<Child callback={() => setIsOpen(false)} />
)
}
const Child (callback) => {
const submitHandler = () => {
postRequest(data); //updates items' data + updates items in the context
callback(); //After closing the modal here, I would like the parent component re-render.
}
return (
<Modal
isOpen={isOpen}
submit={submitHandler}
onClose={callback}
>...
<Modal />
)
}