Reputation: 2549
I'm trying to create a notifications area. I show a notification icon, and when the user clicks on it, I show the list of notifications.
Here's a codesandbox
The problem is that I can't mix it with ClickAwayListener
.
When I use ClickAwayListener
it's not shown at all.
How should I fix this?
HeaderAction.js
import Tooltip from "@material-ui/core/Tooltip";
import Fade from "@material-ui/core/Fade";
import Collapse from "@material-ui/core/Collapse";
import React, { useState } from "react";
import ClickAwayListener from "@material-ui/core/ClickAwayListener";
import Icon from "@material-ui/core/Icon";
const HeaderAction = ({ icon, title, component }) => {
const Component = component || (() => <div>NA</div>);
const [showComponent, setShowComponent] = useState(false);
const handleClick = () => {
setShowComponent(!showComponent);
};
return (
<>
<Tooltip title={title || ""}>
<div onClick={() => handleClick()}>
<Icon>{icon}</Icon>
</div>
</Tooltip>
{/* This part is not working */}
{/* <ClickAwayListener onClickAway={() => setShowComponent(false)}>
<div>
<Fade in={showComponent}>
<div>
<Component />
</div>
</Fade>
</div>
</ClickAwayListener> */}
<Fade in={showComponent}>
<div>
<Component />
</div>
</Fade>
</>
);
};
export { HeaderAction };
Upvotes: 2
Views: 1430
Reputation: 81470
When you click the icon button, handleClick
is called and the showComponent
state is set to true
, but then onClickAway
from ClickAwayListener
is also called and set the showComponent
state to false
again. The fix is simple, don't let the onClickAway
handler execute by stopping the propagation after clicking the button:
<div
onClick={(e) => {
e.stopPropagation();
handleClick();
}}
>
Upvotes: 3