-
Is this a good way to show and hide header with react-native-reanimated? Feels like it works quite well but what do you guys think? How could I improve? const previousScrollY = useSharedValue(0);
const headerOffset = useSharedValue(0);
const scrollHandler = useAnimatedScrollHandler({
onScroll: (event) => {
const currentY = event.contentOffset.y;
if (currentY > previousScrollY.value) {
// Scrolling down: hide the header
const scrollDifference = currentY - previousScrollY.value;
const newOffset = clamp(
headerOffset.value - scrollDifference,
-COLLAPSING_HEADER_HEIGHT,
0,
);
headerOffset.value = newOffset;
} else if (currentY < previousScrollY.value) {
// Scrolling up: show the header
const scrollDifference = previousScrollY.value - currentY;
const newOffset = clamp(
headerOffset.value + scrollDifference,
-COLLAPSING_HEADER_HEIGHT,
0,
);
headerOffset.value = newOffset;
}
const maxScrollY =
event.contentSize.height - event.layoutMeasurement.height;
previousScrollY.value = clamp(currentY, 0, maxScrollY);
},
});
const transformAnim = useAnimatedStyle(() => {
return {
transform: [{ translateY: scrollY.value }],
};
}); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey! Your code looks correct. One thing, I wonder if you need this In the first case, you calculate The result is the same in the second case, when you calculate Wrapping up, your code looks fine but I would try replacing this: if (currentY > previousScrollY.value) {
// Scrolling down: hide the header
const scrollDifference = currentY - previousScrollY.value;
const newOffset = clamp(
headerOffset.value - scrollDifference,
-COLLAPSING_HEADER_HEIGHT,
0,
);
headerOffset.value = newOffset;
} else if (currentY < previousScrollY.value) {
// Scrolling up: show the header
const scrollDifference = previousScrollY.value - currentY;
const newOffset = clamp(
headerOffset.value + scrollDifference,
-COLLAPSING_HEADER_HEIGHT,
0,
);
headerOffset.value = newOffset;
} with just: const newOffset = clamp(
headerOffset.value + previousScrollY.value - currentY,
-COLLAPSING_HEADER_HEIGHT,
0,
);
headerOffset.value = newOffset; |
Beta Was this translation helpful? Give feedback.
Hey!
Your code looks correct. One thing, I wonder if you need this
if ... else if
logic. It seems that the only difference is the way in which you calculate and apply thescrollDifference
.In the first case, you calculate
scrollDifference
ascurrentY - previousScrollY.value
and then, subtract it from theheaderOffset.value
, which gives youheaderOffset.value - (currentY - previousScrollY.value)
, which is the same asheaderOffset.value + previousScrollY.value - currentY
The result is the same in the second case, when you calculate
scrollDifference
aspreviousScrollY.value - currentY
and then, add the result toheaderOffset.value
. You getheaderOffset.value + previousScrollY.value - currentY
,…