Skip to content

Instantly share code, notes, and snippets.

@robbertvancaem
Last active December 9, 2019 22:11
Show Gist options
  • Save robbertvancaem/192292c6e8dd737a674868ea226f022c to your computer and use it in GitHub Desktop.
Save robbertvancaem/192292c6e8dd737a674868ea226f022c to your computer and use it in GitHub Desktop.
parallax-spring-3
import React, { useEffect, useRef } from 'react';
import { animated, useSpring } from 'react-spring';
// You can use this `calc` method to increase the impact
// of the effect by playing around with the values and units.
const calc = o => `translateY(${o * 0.1}px)`;
const Comp = () => {
const ref = useRef();
const [{ offset }, set] = useSpring(() => ({ offset: 0 }));
const handleScroll = () => {
const posY = ref.current.getBoundingClientRect().top;
const offset = window.pageYOffset - posY;
set({ offset });
};
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
});
return (
<div style={{
background: '#123456',
position: 'relative',
width: '100vw',
height: '400px',
ref={ref}
}}>
<animated.div style={{
background: '#654321',
position: 'absolute',
width: '100vw',
height: '100px',
transform: offset.interpolate(calc)
}} />
</div>
)
}
export default Comp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment