Reputation: 189
I have a generic popup component that gets rendered in several other components in my app. what I need to do is to run the onclose function inside the popup whenever one of the containers gets destroyed.
So, of course, I can pass this function in a prop in each one of these containers when its unmounting, but my question is - is it possible to do this only from my popup component? meaning put a listener that will do the job whenever one of the containers will unmount?
Upvotes: 1
Views: 502
Reputation: 10307
Well you can do something with the Context API.
Have the following scenario:
<YourApp>
<PopUpController>
......... all other components whatever here ..........
</PopUpController>
</YourApp>
The PopUpController
is a component that initiates a Context Provider with any helper methods or anything you might want to know about the popups. Methods might be a show
or a hide
method like you want.
// I'm skipping technicalities because I don't know your exact use cases
const PopUpContext = React.createContext();
function PopUpController({ children }) {
const [open, setOpen] = useState(false);
const openPopUp = () => setOpen(true);
const closePopUp = () => setOpen(false);
return (
<PopUpContext.Provider value={{ openPopUp, closePopUp }}>
{children}
</PopUpContext.Provider>
);
}
In any component on the dismount you can simply import the PopUpContext
and use it.
...
const popUpContext = useContext(PopUpContext);
....
useEffect(() => {
...
// on dismount we call the close
return () => {
popUpContext.closePopUp();
}
}, [popUpContext]);
Upvotes: 1