Skip to content

Instantly share code, notes, and snippets.

@MarwanShehata
Last active April 20, 2024 02:17
Show Gist options
  • Save MarwanShehata/49ab23784cd4962b2d15a92917e75721 to your computer and use it in GitHub Desktop.
Save MarwanShehata/49ab23784cd4962b2d15a92917e75721 to your computer and use it in GitHub Desktop.
In this challenge you'll be adding a modal experience to the app. The user needs to be able to open the modal and then close it either by clicking the close icon in the modal itself, or by clicking anywhere outside of the modal. You'll need both c
export default function App() {
const [isOpen, setIsOpen] = React.useState(false);
const ref = React.useRef(null);
React.useEffect(() => {
if (isOpen === true) {
const handleEvent = (e) => {
const element = ref.current;
if (element && !element.contains(e.target)) {
setIsOpen(false);
}
};
document.addEventListener('pointerdown', handleEvent);
return () => {
document.removeEventListener('pointerdown', handleEvent);
};
}
}, [isOpen]);
const handleOpenModal = () => {
if (isOpen === false) {
setIsOpen(true);
}
};
const handleCloseModal = () => {
setIsOpen(false);
};
return (
<>
<section>
<h1>Click Outside</h1>
<button className='link' onClick={handleOpenModal}>
Open Modal
</button>
</section>
{isOpen && (
<dialog ref={ref}>
<button onClick={handleCloseModal}>closeIcon</button>
<h2>Modal</h2>
<p>
Click outside the modal to close (or use the button) whatever you
prefer.
</p>
</dialog>
)}
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment