Last active
January 3, 2021 18:56
-
-
Save ChrisCrossCrash/a015bf6ab5ea2042ca95194b6cfcf576 to your computer and use it in GitHub Desktop.
A parallax background component for use with Gatsby Image and GreenSock ScrollTrigger.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useEffect, useRef} from 'react' | |
import {gsap} from 'gsap' | |
import {ScrollTrigger} from 'gsap/ScrollTrigger' | |
import Img from 'gatsby-image' | |
gsap.registerPlugin(ScrollTrigger) | |
const ParallaxBG = (props) => { | |
const bgRef = useRef(null) | |
const containerRef = useRef(null) | |
useEffect(() => { | |
gsap.fromTo(bgRef.current, { | |
top: window.innerHeight / 2, | |
}, { | |
top: -window.innerHeight / 2, | |
ease: 'none', | |
scrollTrigger: { | |
trigger: containerRef.current, | |
scrub: true, | |
markers: props.markers, | |
}, | |
}) | |
}, []) | |
return ( | |
<div ref={containerRef} {...props}> | |
{/* The gsap animation works on an element's `style` attribute. */} | |
{/* Since the <Img/> element doesn't have a `style` attribute, we need to wrap it with this div. */} | |
<div | |
ref={bgRef} | |
style={{ | |
position: 'fixed', | |
top: 0, | |
height: '100vh', | |
width: '100%', | |
zIndex: -1, | |
}} | |
> | |
<Img | |
fluid={props.fluid} | |
alt='nice' | |
style={{ | |
height: '100%', | |
width: '100%', | |
objectFit: 'cover', | |
}} | |
/> | |
</div> | |
{props.children} | |
</div> | |
) | |
} | |
export default ParallaxBG |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment