Here I have a modal in my react app and its working and if I try to close model with the help of close button it also works but the problem arise when I try to close modal with backdrop here what I simply did is I am executing the same modal close function which I am triggering on close button click and it is also working but is also closes modal whenever I click on the inner modal content which I definitely don't want I want to close it only when I click anywhere except my modal inner content so how can I fix as I tried with the help of z-index but it doesn't work:
React:
import React from "react";
import { useState } from "react";
import classes from "./Cart.module.css";
const Cart = () => {
const [isOpen, setIsOpen] = useState(true);
const closeHandler = () => {
setIsOpen(false);
};
return (
isOpen && (
<div className={classes.modal} onClick={closeHandler}>
<div className={classes.root} onClick={closeHandler}>
<span className={classes.close}>×</span>
<span>Item: Pizza</span>
<span>Price: $50</span>
<span>
<button>Order</button>
</span>
</div>
</div>
)
);
};
export default Cart;
CSS:
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.6);
display: flex;
justify-content: center;
align-items: center;
}
.root {
z-index: 10;
width: 25%;
height: 30%;
padding: 10px;
background-color: #fefefe;
border-radius: 5px;
display: flex;
justify-content: center;
align-items: center;
overflow: auto;
flex-direction: column;
}
.close {
color: #aaa;
font-size: 32px;
font-weight: bold;
position: relative;
left: 48%;
bottom: 29%;
}
.close:hover {
color: red;
cursor: pointer;
}
Pass the event (e) in your closeHandler
and check if className
matches the modal class, only then call setIsOpen(false)
. Try this:
const closeHandler = (e) => {
if (e.target.className === classes.modal) {
setIsOpen(false);
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.