Search code examples
react-nativeanimationscrollreact-native-reanimatedreact-native-reanimated-v2

React-native-reanimated: is there a way to remove a component from the dom when scrolling rather than hide it with style?


I'm able to hide a react-native element using useAnimatedStyle and returning a style that I can apply to my element like opacity: 0 for instance.

But I don't find any way to remove the element from the dom. Using

const handleScroll = useAnimatedScrollHandler(
  {
    onScroll(event) {
      currentPositionY.value = withTiming(event.contentOffset.y, {
        duration: 10,
      });
    },
  },
  []
);

I can only retrieve the value of currentPositionY inside useAnimatedStyle but I would like to find a way to do it directly in the rendering part like:

{currentPositionY > 50 ? <MyComponent/> : null}

Is there a way to achieve this?


Solution

  • Try the useAnimatedReaction hook.

    1. Create a state that controls the element visibility in the DOM
    2. Use the useAnimatedReaction hook, and pass your sharedValue as a dependency
    3. Inside the hook set your visibility state to false based on your logic.