Reputation: 1061
I'm pretty stuck here and there's a good chance I'm going about this all wrong. I'm trying to create an options menu using a series of popup boxes. Basically, the user clicks on the box, some kind of dialog pops up and they either input something or choose something based on the option in question.
I have the logic for clicking and showing popups separated out into another component, ClickablePopup
, which allows me to not repeat the logic for opening and closing the popup. But I am really not sure how to cause the popup to close based on a signal from the children
, which I intend to be able to contain several different kinds of inputs.
The ClickablePopup component I've been trying to use:
const ClickablePopup = ({ children, label }) => {
const [openPopup, setOpenPopup] = useState(false);
const togglePopup = () => {
setOpenPopup(!openPopup);
};
const ref = useDetectClickOutside({
onTriggered: () => {
if (openPopup) {
setOpenPopup(false);
}
}
});
return (
<div ref={ref}>
{openPopup ? (
<>{children}</>
) : (
<div className="badge" onClick={() => togglePopup()}>
{label}
</div>
)}
</div>
);
};
Here is a codesandbox with what I have so far: https://codesandbox.io/s/cra-g8215s?file=/App.js
As mentioned, I'm pretty well stuck because I just can't think of how to get the inside "wrapped" component to send a signal to its wrapper.
Upvotes: 1
Views: 407
Reputation: 141
you can add togglePopup to child ref and use it in parent
https://pl.reactjs.org/docs/hooks-reference.html#useimperativehandle
Upvotes: 1