0

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?

Simon
  • 6,025
  • 7
  • 46
  • 98

1 Answers1

1

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.
Jácint Varga
  • 111
  • 2
  • 7
  • Thanks, I tried this: useAnimatedReaction( () => currentPositionY.value, (result, previous) => { if (result > 200) { setIsHeaderCollapsed(true); } }, [currentPositionY] ); And when result > 200 the app crashes – Simon Feb 07 '23 at 09:17
  • 1
    @Simon You should use 'runOnJS' method for setting the state. [More about it](https://docs.swmansion.com/react-native-reanimated/docs/api/miscellaneous/runOnJS/) – Jácint Varga Feb 07 '23 at 10:48