darrylsyms / fretwise-app-private

0 stars 0 forks source link

Improve My Custom Animated Header #19

Open darrylsyms opened 2 years ago

darrylsyms commented 2 years ago

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 one if (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!

Posted here: https://stackoverflow.com/questions/71749610/conditionally-trigger-animated-timing-from-scrolly-position-of-scrollview