I am working on a Modal and having some issues. I am able to open my Modal, but am unable to close it by clicking outside the "container" id within my Modal.
Home Page
const [showMyModal, setShowMyModal] = useState<boolean>(false)
const handleClose = () => setShowMyModal(false)
const handleOpen = () => setShowMyModal(true)
return (
<div className={style.hero}>
<div>
<h1>Product Page</h1>
<button onClick={handleOpen} className='bg-red-400 text-white px-3 -y-2 rounded hover:scale-95 tarnsition text-xl'>New Product</button>
</div>
{ ProductData && <Table columns={columns} dataSource={ProductData.allProducts} />}
<MyModal onClose={handleClose} visible={showMyModal}/>
</div>
)
Modal Code:
export default function MyModal({visible}: any, {onClose}: any) {
const handleClose =(e:any) => {
if(e.target.id ==='container') onClose();
};
if(!visible) return null
return (
<div id='container' onClick={handleClose} className="fixed inset-0 bg-black bg-opacity-25 backdrop-blur-sm flex items-center justify-center">
//Form is in here
</div>
);
}
Any assistance would be great!
CodePudding user response:
Actually I didn't know what's the problem with your code But I used to handle my modal that way
MyModal.tsx
interface Modal {
visible: boolean;
close: any;
}
export default function MyModal(props: Modal) {
const handleClose = (e: any) => {
if (e.target.id === "container") {
props.close();
}
};
if (!props.visible) return null;
return (
<div id="container" onClick={handleClose} className="modal">
//Form is in here
</div>
);
}
You can call that way
const [showMyModal, setShowMyModal] = useState<boolean>(false);
const handleClose = () => setShowMyModal(false);
const handleOpen = () => setShowMyModal(true);
return (
<div>
<div>
<h1>Product Page</h1>
<button
onClick={handleOpen}
className="bg-red-400 text-white px-3 -y-2 rounded hover:scale-95 tarnsition text-xl"
>
New Product
</button>
</div>
<MyModal {...{ visible: showMyModal, close: handleClose }} />
</div>
);
here is the link if you want to try it. It's working as you want
https://codesandbox.io/s/optimistic-mcclintock-sl5555?file=/src/App.tsx
CodePudding user response:
Something is off with props in your modal currently. Instead of {visible}: any, {onClose}: any
should be {visible: any, onClose: any}