'How can I prevent the onmouseleave event from being triggered outside the browser?
There is a basket. When i enter the mouse, the dropdown opens and shows the items in the basket. When i leave the mouse, the dropdown closes. Inside the dropdown, i have a button for each item to remove items from the basket. When we click the button, a modal pops up, and we approve or reject. When this modal pops up, if we move the mouse away from the browser, onMouseEnter event is triggering and and causing the modal to close. How can i prevent this? I want the modal to close only when I click the backdrop or the reject button.
I passed hideDropdown function to child component(BasketItem) and tried to update isModalShow and dropdown state the same handleClick function. The dropdown closed, but the modal didn't pop up. How can i solve this? Can you help?
Basket component:
const Basket = () => {
const [isDropdownShow, setIsDropdownShow] = useState(false);
const { basket } = useAppContext();
const showDropdown = (e) => {
setIsDropdownShow(true);
};
const hideDropdown = (e) => {
setIsDropdownShow(false);
};
return (
<Wrapper
onMouseEnter={showDropdown}
onMouseLeave={hideDropdown}
isDropdownShow={isDropdownShow}
>
Basket
<span className='basket-length'>{basket.length}</span>
{isDropdownShow && <div className='white-border'></div>}
{basket.length === 0 && isDropdownShow && (
<div className='dropdown empty-basket'>Basket is empty</div>
)}
{isDropdownShow && (
<div className='dropdown'>
<ul>
{basket
.map((basketItem, index) => {
return (
<BasketItem
key={index}
basketItem={basketItem}
hideDropdown={hideDropdown}
/>
);
})
.sort(sortBasket)}
</ul>
</div>
)}
</Wrapper>
);
};
export default Basket;
BasketItem Component:
const BasketItem = ({ basketItem, hideDropdown }) => {
const [isModalShow, setIsModalShow] = useState(false);
const handleClick = () => {
hideDropdown();
setIsModalShow(true); //does not trigger
};
return (
<Wrapper>
<img src={basketItem.image} alt='product-item' />
<div>
<p className='basket-description'>{basketItem.description}</p>
<span className='basket-remove' onClick={handleClick}>
Remove
</span>
<Modal
isModalShow={isModalShow}
onClose={() => setIsModalShow(false)}
/>
</div>
</Wrapper>
);
};
export default BasketItem;
Modal:
const Modal = ({ isModalShow, onClose }) => {
if (!isModalShow) return null;
return ReactDom.createPortal(
<>
<Backdrop />
<Wrapper>
<button onClick={onClose}>CloseModal</button>
some content
</Wrapper>
</>,
document.getElementById('overlays')
);
};
export default Modal;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
