How to make a Header that Animates from Transparent to Opaque Color on Scrolling down in React-Native React Navigation 5?

Viewed 4523

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

2 Answers

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

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}...
Related