screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> const { useState, useRef, useEffect } = React; function App() { const [isModalOpen, setIsModalOpen] = useState(false); const modalRef = useRef(null); useEffect(() => { const closeModalOnClickOutside = (event) => { if (modalRef.current && !modalRef.current.contains(event.target)) { closeModal(); } }; if (isModalOpen) { document.addEventListener('mouseup', closeModalOnClickOutside); } return () => { document.removeEventListener('mouseup', closeModalOnClickOutside); }; }, [isModalOpen]); const openModal = () => { setIsModalOpen(true); }; const closeModal = () => { setIsModalOpen(false); }; return ( <div className='container'> <h3>React Close popup modal onclick outside</h3> <button onClick={openModal} className="open-modal">Open Modal</button> {isModalOpen && ( <div className="modal"> <div className="modal-content" ref={modalRef}> <h3>React Close Modal When Clicked Outside</h3> {/* Modal content here */} <button className="close-button" onClick={closeModal}>Close</button> </div> </div> )} </div> ); } ReactDOM.render(<App />, document.getElementById('app')); </script> <style> .container { text-align: center; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12), 0 2px 4px 0 rgba(0, 0, 0, 0.24); width: 600px; margin: 0 auto; padding: 20px; } .modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; } .modal-content { background-color: white; padding: 20px; border-radius: 5px; max-width: 400px; } .open-modal { background-color: #007bff; color: #fff; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; } .close-button { background-color: #dc3545; color: #fff; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; float: right } /* Hover effect */ .open-modal:hover, .close-button:hover { opacity: 0.8; } </style> </body> </html>