1 year ago
#376780
Dazza
Conditionally trigger Animated.timing from ScrollY position of ScrollView
I've created a template for screens throughout my app. The template utilises Animated Header components that respond to the scrollY position of the ScrollView content.
I'm able to use this scrollY variable to interpolate items, but I can't figure out how to use the variable to trigger Animated.timing
events.
In simple terms:
if (ScrollY > 30)
do Animated.timing oneif (ScrollY < 30)
do Animated.timing two
For now I've created an inadequate workaround using the Animated.event() listener
:
<ScrollView
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: scrollListener } } }],
{
listener: (event) => {
handleScroll(event);
},
}
)}
...
The handleScroll(event)
controls an array of Animated.timing
events, each of which operates conditionally from a setScrollPosition()
useState
variable:
const [scrollPosition, setScrollPosition] = useState(0);
const fixedHeaderTranslatePosition = useRef(new Animated.Value(4)).current;
const handleScroll = (event) => {
setScrollPosition(
event.nativeEvent.contentOffset.y +
(Platform.OS === 'ios' ? HEADER_MAX_HEIGHT : 0)
);
if (scrollPosition > 30 && headerType === 'Animated') {
Animated.timing(fixedHeaderTranslatePosition, {
toValue: 0,
useNativeDriver: true,
}).start();
...
}
Whilst my efforts do create a functional component, there are some minor problems.
Firstly, the event.nativeEvent.contentOffset.y
seems to cause a lag on Android devices. This is most noticeable with the fixedHeaderTranslatePosition
.
Also logically it would make much more sense to utilise the already declared scrollListener
from the Animated.event
. So my question is: How can I utilise the ScrollY
variable (scrollListener
) inside my handleScroll()
? 🤔
The ScrollY
variable is not noted above since it makes more sense in context. Here's a working snack: https://snack.expo.dev/@dazzerr/animated-header-example . You can search for "TODO" to find the areas that I believe require attention.
Thanks in advance!
react-native
react-animated
0 Answers
Your Answer