To stop the main content from scrolling when your mobile header/hamburger menu is open in your React application, you need to apply specific CSS properties to the body element. The most robust way to do this, especially to ensure compatibility across different browsers (including iOS Safari which has known quirks with overflow: hidden), is using a combination of position: fixed and managing the scroll position with JavaScript.
Here's how you can integrate this into your existing React Header component:
1. CSS Adjustments (in your global CSS file, e.g., index.css, or a dedicated Header.css if you import it):
First, ensure your menu-container has the correct positioning and scrolling properties, and define the keyframes for animations.
/* Add these keyframes if they are not already defined */
@keyframes slideIn {
from { opacity: 0; transform: translateX(-20px); }
to { opacity: 1; transform: translateX(0); }
}
@keyframes slideDown {
from { max-height: 0; opacity: 0; }
to { max-height: 500px; opacity: 1; } /* Adjust max-height based on your content */
}
/* Styles for the mobile menu container */
.menu-container {
position: fixed; /* Make it fixed relative to the viewport */
top: 0; /* Align to the very top */
right: 0; /* Or left: 0, if you want it to slide from the left */
width: 100%; /* Default to full width on mobile */
max-width: 300px; /* A common width for side menus, adjust as needed */
height: 100vh; /* Full viewport height */
background-color: white; /* Or your menu's background color */
z-index: 40; /* Lower than your main header (z-50), but above main content */
transform: translateX(100%); /* Start hidden off-screen to the right */
transition: transform 0.3s ease-out; /* Smooth slide-in/out transition */
overflow-y: auto; /* IMPORTANT: Allows the menu content itself to scroll if it's too long */
-webkit-overflow-scrolling: touch; /* Improves scrolling performance on iOS */
padding-top: 80px; /* Adjust this value based on your actual header's combined height (banner + main header) to prevent menu content from being hidden behind it */
box-shadow: -2px 0 10px rgba(0,0,0,0.1); /* Optional: subtle shadow */
}
.menu-container.open {
transform: translateX(0); /* Slide into view */
}
2. React Component (Header.tsx):
We'll use useEffect to manage the body's styles based on the open state. We also need to store the scrollPosition before locking the body.
import { useEffect, useState, useRef } from 'react'; // Import useRef
import { NavLink, useNavigate } from 'react-router-dom';
import { Divide as Hamburger } from 'hamburger-react';
import { headerLinks } from '../Navigation/Navigation';
import { CiUser, CiSearch } from "react-icons/ci";
import { MdKeyboardArrowDown, MdKeyboardArrowRight } from "react-icons/md";
import { FaRupeeSign } from "react-icons/fa";
import { Logo } from '../assets/icons';
import ShippingCurrencyModal from '../components/ShippingCurrencyModal';
import CartModal from '../components/CartModal';
import { perfume1 } from '../assets/images';
import useUserStore from '../store/useUserStore';
export interface HeaderLink {
id: number;
title: string;
link: string;
}
export type DropdownKey = 'Collections' | 'About Us';
export interface DropdownContent {
'Collections': { title: string; path: string; img: string; }[];
'About Us': { title: string; path: string; }[];
}
export interface ActiveDropdowns {
desktop: DropdownKey | null;
mobile: DropdownKey | null;
}
const Header: React.FC = () => {
const navigate = useNavigate();
const {isAuthenticated} = useUserStore();
const [open, setOpen] = useState<boolean>(false);
const [showBanner, setShowBanner] = useState<boolean>(false);
const [activeDropdowns, setActiveDropdowns] = useState<ActiveDropdowns>({
desktop: null,
mobile: null
});
// Use a ref to store the scroll position, so it persists across renders
// without causing extra re-renders when it changes.
const scrollPosition = useRef(0);
// Refs for click outside and focus management
const mobileMenuRef = useRef<HTMLDivElement>(null);
// Hamburger-react doesn't directly expose a ref to its button.
// We'll wrap it in a div or query the DOM if precise focus is needed.
// For now, we'll focus on the div if we add one.
const hamburgerWrapperRef = useRef<HTMLDivElement>(null);
const hasDropdown = (title: string): title is DropdownKey =>
title === 'Collections' || title === 'About Us';
const dropdownContent: DropdownContent = {
'Collections': [
{ title: 'Western Winds', path: '/collections/western-winds/1', img: perfume1 },
{ title: 'All Attars', path: '/collections/attars/2', img: perfume1 },
{ title: 'All Perfumes', path: '/collections/perfumes/3', img: perfume1 },
{ title: 'East Meets The West', path: '/collections/east-west/4', img: perfume1 },
{ title: 'Eastern Treasures', path: '/collections/eastern/5', img: perfume1 },
{ title: 'Discovery Sets', path: '/collections/discovery/6', img: perfume1 }
],
'About Us': [
{ title: 'Our Story', path: '/about/story' },
{ title: 'Our Logo', path: '/about/logo' },
{ title: 'Our Founder', path: '/about/founder' }
]
};
const getLinkClassName = ({ isActive }: { isActive: boolean }): string => {
return `text-xs lg:text-[0.90rem] tracking-[1px] leading-[1.125rem]
uppercase font-bold transition-colors
${isActive ? 'text-gray-500' : 'hover:text-gray-500'}`;
};
const toggleDropdown = (type: keyof ActiveDropdowns, title: string): void => {
if (hasDropdown(title)) {
setActiveDropdowns(prev => ({
...prev,
[type]: prev[type] === title ? null : title
}));
}
};
const headerClasses = `
w-full
fixed
z-50
transition-all
duration-300
bg-white
text-black
`;
useEffect(() => {
const timer = setTimeout(() => {
setShowBanner(true);
}, 2000);
return () => clearTimeout(timer);
}, []);
// --- START: Scroll Locking Logic ---
useEffect(() => {
const body = document.body;
// Store original body styles to restore them later
const originalBodyStyle = {
overflow: body.style.overflow,
position: body.style.position,
top: body.style.top,
width: body.style.width,
// paddingRight: body.style.paddingRight // Uncomment if you add scrollbar compensation
};
if (open) {
// Menu is opening: Lock the body scroll
scrollPosition.current = window.scrollY; // Capture current scroll position
body.style.overflow = 'hidden'; // Hide body scrollbar
body.style.position = 'fixed'; // Fix body position
body.style.top = `-${scrollPosition.current}px`; // Shift body up to current scroll position
body.style.width = '100%'; // Ensure body width is 100% when fixed
// Optional: Add padding-right to compensate for scrollbar if present,
// to prevent layout shift. This is often not needed with `position: fixed`
// on the body, but can be an edge case.
// const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
// if (scrollbarWidth > 0) {
// body.style.paddingRight = `${scrollbarWidth}px`;
// }
} else {
// Menu is closing: Restore body scroll
body.style.overflow = originalBodyStyle.overflow;
body.style.position = originalBodyStyle.position;
body.style.top = originalBodyStyle.top;
body.style.width = originalBodyStyle.width;
// body.style.paddingRight = originalBodyStyle.paddingRight; // Uncomment if used
window.scrollTo(0, scrollPosition.current); // Restore scroll position
}
// Cleanup function: important for React useEffect
return () => {
// Ensure styles are reverted if component unmounts or 'open' state changes
body.style.overflow = originalBodyStyle.overflow;
body.style.position = originalBodyStyle.position;
body.style.top = originalBodyStyle.top;
body.style.width = originalBodyStyle.width;
// body.style.paddingRight = originalBodyStyle.paddingRight; // Uncomment if used
// No need to scrollTo here, as the 'open' state change handler handles it.
};
}, [open]); // Re-run this effect whenever the 'open' state changes
// --- END: Scroll Locking Logic ---
// --- START: Close Menu on Click Outside/Escape Key ---
useEffect(() => {
const handleOutsideClick = (event: MouseEvent) => {
// Check if the click occurred outside the mobile menu and outside the hamburger button wrapper
if (
open &&
mobileMenuRef.current &&
!mobileMenuRef.current.contains(event.target as Node) &&
hamburgerWrapperRef.current &&
!hamburgerWrapperRef.current.contains(event.target as Node)
) {
setOpen(false); // Close the menu
setActiveDropdowns(prev => ({ ...prev, mobile: null })); // Reset any open mobile dropdowns
}
};
const handleEscapeKey = (event: KeyboardEvent) => {
if (event.key === 'Escape' && open) {
setOpen(false); // Close the menu
setActiveDropdowns(prev => ({ ...prev, mobile: null })); // Reset any open mobile dropdowns
// Return focus to the hamburger button for accessibility if needed
// hamburgerWrapperRef.current?.focus(); // This would focus the wrapper div
}
};
if (open) {
document.addEventListener('mousedown', handleOutsideClick);
document.addEventListener('keydown', handleEscapeKey);
}
return () => {
document.removeEventListener('mousedown', handleOutsideClick);
document.removeEventListener('keydown', handleEscapeKey);
};
}, [open]); // Re-run this effect whenever the 'open' state changes
// --- END: Close Menu on Click Outside/Escape Key ---
const renderDropdown = (title: DropdownKey) => {
if (title === 'Collections') {
return (
<div className="absolute grid grid-cols-3 gap-5 top-16 -left-0 w-screen bg-white shadow-lg py-8 px-16">
{dropdownContent[title].map((item, index) => (
<div key={index} className="flex items-center">
<img src={item.img} alt={item.title} className="w-16 h-10 rounded-lg" />
<NavLink
to={item.path}
className={({ isActive }) => `block px-4 py-2 text-lg transition-colors
${isActive ? 'bg-gray-50 text-gray-400' : 'hover:bg-gray-50'}`}
onClick={() => setActiveDropdowns(prev => ({ ...prev, desktop: null }))}
>
{item.title}
</NavLink>
</div>
))}
</div>
);
}
if (title === 'About Us') {
return (
<div className="absolute grid grid-cols-3 gap-5 top-16 -left-0 w-screen bg-white shadow-lg py-8 px-16">
{dropdownContent[title].map((item, index) => (
<NavLink
key={index}
to={item.path}
className={({ isActive }) => `block px-4 py-2 text-lg transition-colors
${isActive ? 'bg-gray-50 text-gray-400' : 'hover:bg-gray-50'}`}
onClick={() => setActiveDropdowns(prev => ({ ...prev, desktop: null }))}
>
{item.title}
</NavLink>
))}
</div>
);
}
};
const renderMobileMenu = () => {
// If a dropdown is active, only show that section
if (activeDropdowns.mobile) {
const dropdownData = dropdownContent[activeDropdowns.mobile];
return (
<nav className="px-4 py-6 border-t">
<button
onClick={() => setActiveDropdowns(prev => ({ ...prev, mobile: null }))}
className="flex items-center justify-between w-full py-3 text-sm uppercase tracking-wider group"
>
<MdKeyboardArrowRight
className="w-5 h-5 rotate-180 transition-transform duration-300 ease-in-out group-hover:-translate-x-1" // Changed to rotate-180 for "back" arrow
/>
Back to {activeDropdowns.mobile}
</button>
<div
className="pl-4 transition-all duration-300 ease-in-out transform origin-top"
style={{
animation: "slideDown 0.3s ease-out forwards"
}}
>
{dropdownData.map((item, index) => (
<NavLink
key={index}
to={item.path}
className={({ isActive }) =>
`block py-2 text-lg tracking-widest transition-colors duration-200 transform translate-x-0 hover:translate-x-2 ${
isActive ? 'text-gray-400' : 'text-gray-600 hover:text-gray-300'
}`
}
style={{
animationDelay: `${index * 50}ms`,
animation: "slideIn 0.3s ease-out forwards"
}}
onClick={() => {
setOpen(false); // Close the overall menu when a menu item is clicked
setActiveDropdowns(prev => ({ ...prev, mobile: null })); // Reset dropdown state
}}
>
{item.title}
</NavLink>
))}
</div>
</nav>
);
}
// Show main menu when no dropdown is active
return (
<nav className="px-4 py-6 border-t">
{headerLinks.map((link, index) => (
<div
key={link.id}
className="transform transition-all duration-300 ease-in-out"
style={{
animation: "slideIn 0.3s ease-out forwards",
animationDelay: `${index * 50}ms`
}}
>
{hasDropdown(link.title) ? (
<button
onClick={() => toggleDropdown('mobile', link.title)}
className="flex items-center justify-between w-full py-3 text-lg tracking-wider group"
>
{link.title}
<MdKeyboardArrowRight
className="w-5 h-5 transition-transform duration-300 ease-in-out group-hover:translate-x-1"
/>
</button>
) : (
<NavLink
to={link.link}
className={({ isActive }) =>
`block py-3 text-lg tracking-wider transition-all duration-200 transform translate-x-0 hover:translate-x-2 ${
isActive ? 'text-gray-500' : ''
}`
}
onClick={() => setOpen(false)} // Close the overall menu when a main link is clicked
>
{link.title}
</NavLink>
)}
</div>
))}
<ShippingCurrencyModal />
</nav>
);
};
return (
<header className={headerClasses}>
{/* Announcement Banner */}
<div
className={`
w-full
bg-[#696969]
text-white
text-center
lg:py-1
py-2
text-xs
lg:text-sm
transition-all
duration-500
transform
${showBanner ? 'translate-y-0 opacity-100' : '-translate-y-full opacity-0'}
`}
>
<p className="flex items-center tracking-widest justify-center gap-1">
Free shipping to INDIA on all orders above
<span className="flex items-center">
<FaRupeeSign className="w-3 h-3" />
690
</span>
</p>
</div>
{/* Desktop Navigation */}
<div className="hidden xl:flex relative justify-between items-center lg:pr-20 lg:pl-4 py-1">
<div className='flex items-center gap-32 pl-2'>
{/* Logo Section */}
<div onClick={() => navigate("/")} className="flex flex-col items-center cursor-pointer">
<img
className="w-[40px] max-w-[7rem] mb-1"
src={Logo}
alt="Shukriya Logo"
/>
<div className='-mt-2 flex flex-col items-center gap-0'>
<h1 className="text-[1.3rem] uppercase font-bold leading-tight">Shukriya</h1>
<p className="text-[0.7rem] -mt-2 uppercase font-bold">Parfumerie</p>
</div>
</div>
{/* Navigation Links */}
<nav className="flex items-center gap-8">
{headerLinks.map((link) => (
<div key={link.id} className="group">
{hasDropdown(link.title) ? (
<div>
<button
className={getLinkClassName({ isActive: activeDropdowns.desktop === link.title })}
onClick={() => toggleDropdown('desktop', link.title)}
>
<span className="flex items-center gap-1">
{link.title}
<MdKeyboardArrowDown
className={`w-5 h-5 transition-transform ${
activeDropdowns.desktop === link.title ? 'rotate-180' : ''
}`}
/>
</span>
</button>
{activeDropdowns.desktop === link.title && renderDropdown(link.title as DropdownKey)}
</div>
) : (
<NavLink
to={link.link}
className={getLinkClassName}
>
{link.title}
</NavLink>
)}
</div>
))}
{/* Currency Display for Desktop */}
<ShippingCurrencyModal />
</nav>
</div>
{/* Icons Section */}
<div className="flex items-center gap-3">
<NavLink to="/search" className={({ isActive }) =>
`hover:text-gray-500 transition-colors ${isActive ? 'text-gray-500' : ''}`}>
<CiSearch className="w-5 h-5" />
</NavLink>
<NavLink to={isAuthenticated ? "/profile" : "/login"} className={({ isActive }) =>
`hover:text-gray-500 transition-colors ${isActive ? 'text-gray-500' : ''}`}>
<CiUser className="w-5 h-5" />
</NavLink>
<CartModal />
</div>
</div>
{/* Mobile Navigation */}
<div className="xl:hidden">
<div className="flex items-center justify-between px-4 py-3">
{/* Mobile Logo */}
<div onClick={() => navigate("/")} className="flex flex-col cursor-pointer items-center">
<img
className="w-[30px] max-w-[5rem]"
src={Logo}
alt="Shukriya Logo"
/>
<h1 className="text-lg uppercase font-bold leading-tight">Shukriya</h1>
<p className="text-xs uppercase font-bold leading-3">Parfumerie</p>
</div>
{/* Mobile Icons */}
<div className="flex items-center gap-4">
<div className="flex items-center gap-3">
<NavLink to="/search" className={({ isActive }) =>
`hover:text-gray-500 transition-colors ${isActive ? 'text-gray-500' : ''}`}>
<CiSearch className="w-5 h-5" />
</NavLink>
<NavLink to={isAuthenticated ? "/profile" : "/login"} className={({ isActive }) =>
`hover:text-gray-500 transition-colors ${isActive ? 'text-gray-500' : ''}`}>
<CiUser className="w-5 h-5" />
</NavLink>
<CartModal />
</div>
{/* Wrap Hamburger in a div to attach ref for click-outside logic */}
<div ref={hamburgerWrapperRef}>
<Hamburger
rounded
toggled={open}
toggle={setOpen} // This correctly sets the 'open' state
color="#000"
size={20}
/>
</div>
</div>
</div>
{/* Mobile Menu Container - attach ref here */}
<div ref={mobileMenuRef} className={`menu-container ${open ? "open" : ""}`}>
{renderMobileMenu()}
</div>
</div>
</header>
);
};
export default Header;