forked from crowetic/commerce
Improve navbar performance
This commit is contained in:
parent
1db974dabd
commit
2613a5cec7
@ -1,30 +1,12 @@
|
||||
import { FC, useState, useEffect } from 'react'
|
||||
import { FC } from 'react'
|
||||
import Link from 'next/link'
|
||||
import s from './Navbar.module.css'
|
||||
import { Logo, Container } from '@components/ui'
|
||||
import { Searchbar, UserNav } from '@components/common'
|
||||
import cn from 'classnames'
|
||||
import throttle from 'lodash.throttle'
|
||||
import NavbarRoot from './NavbarRoot'
|
||||
import s from './Navbar.module.css'
|
||||
|
||||
const Navbar: FC = () => {
|
||||
const [hasScrolled, setHasScrolled] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const handleScroll = throttle(() => {
|
||||
const offset = 0
|
||||
const { scrollTop } = document.documentElement
|
||||
const scrolled = scrollTop > offset
|
||||
setHasScrolled(scrolled)
|
||||
}, 200)
|
||||
|
||||
document.addEventListener('scroll', handleScroll)
|
||||
return () => {
|
||||
document.removeEventListener('scroll', handleScroll)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className={cn(s.root, { 'shadow-magical': hasScrolled })}>
|
||||
const Navbar: FC = () => (
|
||||
<NavbarRoot>
|
||||
<Container>
|
||||
<div className="relative flex flex-row justify-between py-4 align-center md:py-6">
|
||||
<div className="flex items-center flex-1">
|
||||
@ -59,8 +41,7 @@ const Navbar: FC = () => {
|
||||
<Searchbar id="mobile-search" />
|
||||
</div>
|
||||
</Container>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</NavbarRoot>
|
||||
)
|
||||
|
||||
export default Navbar
|
||||
|
33
components/common/Navbar/NavbarRoot.tsx
Normal file
33
components/common/Navbar/NavbarRoot.tsx
Normal file
@ -0,0 +1,33 @@
|
||||
import { FC, useState, useEffect } from 'react'
|
||||
import throttle from 'lodash.throttle'
|
||||
import cn from 'classnames'
|
||||
import s from './Navbar.module.css'
|
||||
|
||||
const NavbarRoot: FC = ({ children }) => {
|
||||
const [hasScrolled, setHasScrolled] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const handleScroll = throttle(() => {
|
||||
const offset = 0
|
||||
const { scrollTop } = document.documentElement
|
||||
const scrolled = scrollTop > offset
|
||||
|
||||
if (hasScrolled !== scrolled) {
|
||||
setHasScrolled(scrolled)
|
||||
}
|
||||
}, 200)
|
||||
|
||||
document.addEventListener('scroll', handleScroll)
|
||||
return () => {
|
||||
document.removeEventListener('scroll', handleScroll)
|
||||
}
|
||||
}, [hasScrolled])
|
||||
|
||||
return (
|
||||
<div className={cn(s.root, { 'shadow-magical': hasScrolled })}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default NavbarRoot
|
Loading…
x
Reference in New Issue
Block a user