Код: Выделить всё
Navbar.jsxКод: Выделить всё
// Array that features all nav-links required. Will return in .map component
const navigation = [
{_id:101, title: 'HOME', href: '/'},
{_id:102, title: 'ABOUT US', href: '/AboutUs'},
{_id:103, title: 'SHOP', href: '/Shop'},
{_id:104, title: 'MENU', href: '/Menu'},
{_id:105, title: 'CONTACT US', href: '/ContactUs'},
];
const Navbar = () => {
const { pathname } = useLocation();
const active = useLocation().pathname; // returns current location and url
const [colour, setColour] = useState(false); // changes the state of colour upon scrolling
const [cartOpen, setCartOpen] = useState(false) // Opens and closes cart
const close = () => setCartOpen(false);
const open = () => setCartOpen(true)
useEffect(() => {
close();
const changeColour = () => {
const isHome = matchPath("/", pathname)
const isAboutUs = matchPath("/AboutUs", pathname)
...
if (isHome && window.scrollY >= 650) {
setColour(true)
} else if (isAboutUs && window.scrollY >= 1) {
setColour(true)
} ...
};
// invoke once to check in case page is already scrolled down when rendering
changeColour();
window.addEventListener('scroll', changeColour);
return () => {
window.removeEventListener('scroll', changeColour)
}
}, [pathname])
return (
...
)
}
Код: Выделить всё
const navigation = [
{ _id:101, title: 'HOME', href: '/' },
{ _id:102, title: 'ABOUT US', href: '/about' },
{ _id:103, title: 'SHOP', href: '/shop' },
{ _id:104, title: 'MENU', href: '/menu' },
{ _id:105, title: 'CONTACT US', href: '/contact' },
];
const Navbar = () => {
const { pathname } = usePathname();
const [colourOnScroll, setColourOnScroll] = useState(false); // changes the state of colour upon scrolling
const [cartOpen, setCartOpen] = useState(false) // Opens and closes cart
const close = () => setCartOpen(false);
const open = () => setCartOpen(true)
// colourOnScroll logic
const changeColourOnScroll = () => {
const scrollThresholds = {
'/': 650,
'/about': 1,
...
};
const threshold = scrollThresholds[pathname] || 0;
if (window.scrollY >= threshold) {
setColourOnScroll(true)
} else {
setColourOnScroll(false)
}
}
useEffect(() => {
close();
const handleScroll = () => {
changeColourOnScroll();
}
changeColourOnScroll(); // Invoke on scroll mount
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll)
}
}, [pathname])
return (
...
)
Подробнее здесь: https://stackoverflow.com/questions/793 ... in-next-js