How to animate header to show based on scrolling in react native?

Andrew Est picture Andrew Est · Oct 8, 2019 · Viewed 8.2k times · Source

So Ideally, When i scroll down, I want the header to disappear(slide down) and when I scroll up I want it to show (slide up). Idc where im at in the page. I just want the animation to fire when those 2 events occur. I see some apps have this but I can't think of how to replicate it. please help me set a basis for this

Answer

chin8628 picture chin8628 · Oct 8, 2019

You can use Animated.FlatList or Animated.ScrollView to make the scroll view, and attach a callback to listen onScroll event when it is changed. Then, using interpolation to map value between y-axis and opacity.

searchBarOpacityAnim is a component's state. By using Animated.event, the state will be updated when a callback is called. Also, don't forget to set useNativeDriver to be true. I've attached the link to document below about why you have to set it.

<Animated.FlatList
  ...
  onScroll={Animated.event(
    [{ nativeEvent: { contentOffset: { y: searchBarOpacityAnim } } }],
    { useNativeDriver: true },
  )}
  ...
/>

Then, use Animated.View wraps your component which you want to animate it. Use .interpolate to map value between the state and component's opacity like the example below...

<Animated.View
  style={{
    opacity: searchBarOpacityAnim.interpolate({
      inputRange: [213, 215],
      outputRange: [0, 1],
    }),
  }}
>
  <SearchBar />
</Animated.View>

You can read more information about useNativeDriver, .interpolate, and Animated.event here.

https://facebook.github.io/react-native/docs/animated#using-the-native-driver

https://facebook.github.io/react-native/docs/animations#interpolation

https://facebook.github.io/react-native/docs/animated#handling-gestures-and-other-events