import { useRef, useState } from 'react'
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/dist/ScrollTrigger'
import { HeaderContainer } from './header.styled'
import { useWindowScrolling } from 'hooks/useWindowScrolling'
import { useIsomorphicLayoutEffect } from 'hooks/useIsomorphicEffect' // It is useEffect
gsap.registerPlugin(ScrollTrigger)
const Header = () => {
const animateRevealOffset = 122
const animationFadeOffset = 175
const ref = useRef<HTMLDivElement>(null)
const [animationRevealed, setAnimationRevealed] = useState(false)
const [direction, scrollTop] = useWindowScrolling() // give the window.scrollY and scroll direction
useIsomorphicLayoutEffect(() => {
if (!ref.current) {
return
}
if (
direction === 'down' &&
scrollTop >= animateRevealOffset - 2 &&
!animationRevealed
) {
console.log('reveal')
ref.current.style.top = -52 + 'px'
setAnimationRevealed(true)
}
if (
direction === 'up' &&
scrollTop <= animateRevealOffset - 2 &&
animationRevealed
) {
console.log('hide')
ref.current.style.top = 20 + 'px'
setAnimationRevealed(false)
}
}, [scrollTop])
useIsomorphicLayoutEffect(() => {
const anim = gsap
.from(ref.current, {
top: 0,
position: 'fixed',
paused: true,
})
.progress(1)
ScrollTrigger.create({
scrub: true,
start: '+=' + animateRevealOffset,
end: '+=' + 52,
markers: true,
onUpdate: (self) => {
self.direction === 1 ? anim.play() : anim.reverse()
},
})
}, [])
return (
<HeaderContainer ref={ref}>
Google
</HeaderContainer>
)
}
export default Header
This is the code for header that i created but it doesn't yield the exact google like animation. On google when window.ScrollY reaches 122, top=-52px is set on the header and then between window.ScrollY=122 to 174 the animation happens and while scrolling up at window.ScrollY=122 the top is set back to 20px and position absolute.