tailwind-nextjs-blog/components/MobileNav.tsx

74 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-10-17 23:37:01 +08:00
import { useState } from 'react';
import Link from './Link';
import headerNavLinks from '@/data/headerNavLinks';
2022-07-17 21:40:41 +08:00
const MobileNav = () => {
2022-10-17 23:37:01 +08:00
const [navShow, setNavShow] = useState(false);
2022-07-17 21:40:41 +08:00
const onToggleNav = () => {
setNavShow((status) => {
if (status) {
2022-10-17 23:37:01 +08:00
document.body.style.overflow = 'auto';
2022-07-17 21:40:41 +08:00
} else {
// Prevent scrolling
2022-10-17 23:37:01 +08:00
document.body.style.overflow = 'hidden';
2022-07-17 21:40:41 +08:00
}
2022-10-17 23:37:01 +08:00
return !status;
});
};
2022-07-17 21:40:41 +08:00
return (
<div className="sm:hidden">
<button
type="button"
className="ml-1 mr-1 h-8 w-8 rounded py-1"
aria-label="Toggle Menu"
2022-10-17 23:37:01 +08:00
onClick={onToggleNav}>
2022-07-17 21:40:41 +08:00
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
2022-10-17 23:37:01 +08:00
className="text-gray-900 dark:text-gray-100">
{navShow ? (
<path
fillRule="evenodd"
d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
clipRule="evenodd"
/>
) : (
<path
fillRule="evenodd"
d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 15a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z"
clipRule="evenodd"
/>
)}
2022-07-17 21:40:41 +08:00
</svg>
</button>
<div
className={`fixed top-24 right-0 z-10 h-full w-full transform bg-gray-200 opacity-95 duration-300 ease-in-out dark:bg-gray-800 ${
2022-07-17 21:40:41 +08:00
navShow ? 'translate-x-0' : 'translate-x-full'
2022-10-17 23:37:01 +08:00
}`}>
<button
type="button"
aria-label="toggle modal"
className="fixed h-full w-full cursor-auto focus:outline-none"
2022-10-17 23:37:01 +08:00
onClick={onToggleNav}></button>
2022-07-17 21:40:41 +08:00
<nav className="fixed mt-8 h-full">
{headerNavLinks.map((link) => (
<div key={link.title} className="px-12 py-4">
<Link
href={link.href}
className="text-2xl font-bold tracking-widest text-gray-900 dark:text-gray-100"
2022-10-17 23:37:01 +08:00
onClick={onToggleNav}>
2022-07-17 21:40:41 +08:00
{link.title}
</Link>
</div>
))}
</nav>
</div>
</div>
2022-10-17 23:37:01 +08:00
);
};
2022-07-17 21:40:41 +08:00
2022-10-17 23:37:01 +08:00
export default MobileNav;