Skip to content

Commit

Permalink
Fix: navbar should close when user click anywhere on screen (#565)
Browse files Browse the repository at this point in the history
* fix navbar close when click anywhere on screen

* removed unnecessary file

* Made requested change

* Rename handleClickOutside function to handleCloseNavbar
  • Loading branch information
lalitkumawat1m authored Apr 1, 2024
1 parent a4bd3ba commit 2934547
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions components/Layout.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useContext, useEffect, useState } from 'react';
import React, { useContext, useEffect, useState, useRef } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import classnames from 'classnames';
Expand Down Expand Up @@ -30,6 +30,8 @@ export default function Layout({

const router = useRouter();

const mobileNavRef = useRef<HTMLDivElement>(null);

React.useEffect(
() => useStore.setState({ overlayNavigation: null }),
[router.asPath],
Expand All @@ -48,6 +50,21 @@ export default function Layout({
}
}, []);

useEffect(() => {
const handleCloseNavbar = (event: MouseEvent) => {
if (
mobileNavRef.current &&
(mobileNavRef.current as any).contains(event.target)
) {
useStore.setState({ overlayNavigation: null });
}
};

document.addEventListener('click', handleCloseNavbar);

return () => document.removeEventListener('click', handleCloseNavbar);
}, [mobileNavRef]);

const newTitle = `JSON Schema${metaTitle ? ` - ${metaTitle}` : ''}`;
return (
<div className='min-h-screen relative flex flex-col justify-between '>
Expand Down Expand Up @@ -84,7 +101,7 @@ export default function Layout({
</div>
</header>
{showMobileNav ? (
<div>
<div ref={mobileNavRef}>
<MobileNav />
{children}
</div>
Expand Down

0 comments on commit 2934547

Please sign in to comment.