3

I am trying to hide and show the header based on the scroll event from reanimated 2 useAnimatedScrollHandler and I need to use the diffClamp so whenever the user scrolls up the header should be shown in less time than the whole scroll event contentOffset.y value but the problem is diffClamp is I think from reanimated v1 and I need to use useAnimatedStyle hook in order to animate styles in reanimated v2 and finally it gives an error.

Can someone please help with it?

Habib Payenda
  • 31
  • 1
  • 3

1 Answers1

5
const clamp = (value, lowerBound, upperBound) => {
    "worklet";
    return Math.min(Math.max(lowerBound, value), upperBound);
};

const scrollClamp = useSharedValue(0);

const scrollHandler = useAnimatedScrollHandler({
    onScroll: (event, ctx) => {

        const diff = event.contentOffset.y - ctx.prevY;

        scrollClamp.value = clamp(scrollClamp.value + diff, 0, 200);

    },
    onBeginDrag: (event, ctx) => {
        ctx.prevY = event.contentOffset.y;
    }
});

const RStyle = useAnimatedStyle(() => {

    const interpolateY = interpolate(
        scrollClamp.value,
        [0, 200],
        [0, -200],
        Extrapolate.CLAMP
    )

    return {
        transform: [
            { translateY: interpolateY }
        ]
    }
})
tungnguyen
  • 51
  • 4
  • If this is the code to your original question, it would make more sense to edit the original question with the code added to it – web_walkerX Jul 16 '21 at 23:14
  • Great answer, this is also a helpful thread on the issue - https://github.com/software-mansion/react-native-reanimated/discussions/1573 – Noitidart Jan 15 '22 at 18:37
  • theres no update on prevY so it wont work as expected. – MichałKraków Jul 08 '22 at 11:54
  • const scrollHandler = useAnimatedScrollHandler({ onScroll: (event, ctx) => { const diff = event.contentOffset.y - ctx.prevY; scrollClamp.value = clamp(scrollClamp.value + diff, 0, headerHeight); ctx.prevY = event.contentOffset.y; }, onBeginDrag: (event, ctx) => { ctx.prevY = event.contentOffset.y } }); – MichałKraków Jul 08 '22 at 12:22