6

I'm trying to make header that will animate from transparent to solid opaque color upon scrolling down using in React-Native React Navigation 5.

Starts to transition to opaque when scrolling halfway

enter image description here


Becomes fully opaque when reach the maximum offset

enter image description here

kaizen
  • 1,580
  • 4
  • 26
  • 50

2 Answers2

12

You can do this by setting the header style opacity to an animated value.

First define your animated value, we'll interpolate the yOffset to get the opacity desired.

const yOffset = useRef(new Animated.Value(0)).current;
const headerOpacity = yOffset.interpolate({
  inputRange: [0, 200],
  outputRange: [0, 1],
  extrapolate: "clamp",
});

then you want to attach an animated.event listener to an animated scroll view

<Animated.ScrollView
  onScroll={Animated.event(
    [
      {
        nativeEvent: {
          contentOffset: {
            y: yOffset,
          },
        },
      },
    ],
    { useNativeDriver: true }
  )}
  scrollEventThrottle={16}
>

Your content should be inside the scroll view

In your screen add a on mount or use effect where you set the animatedValue as the header opacity

useEffect(() => {
  navigation.setOptions({
    headerStyle: {
      opacity: headerOpacity,
    },
    headerBackground: () => (
      <Animated.View
        style={{
          backgroundColor: "white",
          ...StyleSheet.absoluteFillObject,
          opacity: headerOpacity,
        }}
      />
    ),
    headerTransparent: true,
  });
}, [headerOpacity, navigation]);

I've used header transparent and header background so that the background component changes also.

Here is an example:

https://snack.expo.io/@dannyhw/react-navigation-animated-header

Danny
  • 895
  • 11
  • 21
0
const handleScroll = () => {
  YourElementRef.current.style.backgroundColor = `rgba(245, 245, 245, ${window.scrollY > 300 ? 1 : '0.' + (window.scrollY * 3)})`;
}
window.addEventListener('scroll', handleScroll, true);

You need to add scroll listener and call function that animates it. The scroll element is represented by a ref stuff. e.g.

const YourElementRef = React.useRef(null);
<SomeElement ref={YourElementRef}...
D.R.Bendanillo
  • 307
  • 4
  • 7
  • This would work on plain React.js, but not React Native. It's quite different to implement animation to native apps from web. – Yongky Ali Nov 24 '21 at 18:16