Reputation:
Actually, I use isAvatarUserMenuOpen
prop into the UserDataPresentation
class, to know if the modal is opened or not. I use this state to generate a condition that affect the onClick to open and close the modal. But i need to close this modal with any click made outside this modal, actually it only closes in the same button that open it.
I have been doing a handleClick, that add a listener when the modal is opened, and when i click outside the modal, it shows an alert "close de modal!". I need to remove this alert, and find a way to close the modal, just as the onclick that open and close the modal do.
export class UserDataPresentation extends React.Component<Props> {
node: any
componentWillMount() {
document.addEventListener('mousedown', this.handleClick, false)
}
componentWillUnmount() {
document.removeEventListener('mousedown', this.handleClick, false)
}
handleClick = (e: { target: any }) => {
if (!this.node.contains(e.target)) {
alert('close de modal!')
return
}
}
render() {
const { openMenuUserModal, closeMenuUserModal, isAvatarUserMenuOpen } = this.props
return (
<React.Fragment>
<div className="user-data-container" ref={isAvatarUserMenuOpen ? (node) => (this.node = node) : null}>
<div className="text">
<p>Wolfgang Amadeus</p>
</div>
<div className="avatar">
<img src={avatarPhoto} />
</div>
<a href="#" onClick={isAvatarUserMenuOpen ? closeMenuUserModal : openMenuUserModal}>
<div className="svg2">
<SVG src={downArrow} cacheGetRequests={true} />
</div>
</a>
</div>
</React.Fragment>
)
}
}
Upvotes: 0
Views: 1365
Reputation:
I come across this problem quite often and always do the following.
I mix css positioning and react hooks to create a modal. the overlayer div covers the whole div container so when you click any where in the container apart from the modal, the modal dissapears. z-index:1 on #modal makes sure the modal is stacked above the overlayer.
const Modal = () => {
const [modal, setModal] = React.useState(false);
return (
<div id='container'>
<button onClick={() => setModal(true)}>toggle modal</button>
{modal && <div id='overlayer' onClick={() => setModal(false)}></div>}
{modal && <div id='modal'>modal</div>}
</div>
);
};
ReactDOM.render(<Modal/>, document.getElementById("react"));
#container{
position: relative;
height: 200px; width:200px;
border: 1px solid black;
}
#container * {position: absolute;}
#overlayer{
height: 100%; width:100%;
}
#modal{
background: blue;
height: 30%; width:30%;
top: 12%; z-index: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Upvotes: 1
Reputation: 11027
You should be able to call this.props.closeMenuUserModal()
in your handleClick function.
Upvotes: 0