Search code examples
reactjsreact-nativecss-animationsreact-animated

Animate on removal from dom


What is the correct way to do animations when removing something from the DOM?

It seems like no matter what I do, when I remove something form the dom, it doesn't trigger a re render until the items are removed and then it snaps away out of view instead of transitioning before it removes the data. Here is an example of something I've tried.

  const [isExpanded, setIsExpanded] = useState(false);
  const [isVisible, setIsVisible] = useState(false);

  const toggleReplies = () => {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);

    if (isExpanded) {
      setIsVisible(false);
      setTimeout(() => {
        setIsExpanded(false);
      }, 300);
    } else {
      setIsExpanded(true);
      setIsVisible(true);
    }
  };

  return (
    <View style={styles.container}>
      <Button title="Toggle Replies" onPress={toggleReplies} />
      {isVisible && (
        <View style={styles.replyBox}>
          <Text>This is a reply!</Text>
        </View>
      )}
    </View>
  );
};

Solution

  • I don't know what exactly you want to do with fading out, but definitely, your solution is animation, I think the following codes can help you reach your goal:

    import React from 'react';
    import type {FC, ReactNode} from 'react';
    import Animated, {
      FadeInUp,
      FadeOutUp,
      useAnimatedStyle,
      useSharedValue,
    } from 'react-native-reanimated';
    
    
    interface FadeViewProps {
      id: string | number; // <== pass a unique id here
      children?: ReactNode;
    }
    
    const FadeView: FC<FadeViewProps> = ({ id, children }) => {
      const opacity = useSharedValue(1);
    
      const wrapperAnimantedStype = useAnimatedStyle(() => {
        opacity: opacity.value,
      });
    
      return (
        <Animated.View
          key={id}
          entering={FadeInUp}
          exiting={FadeOutUp}
          style={[wrapperAnimantedStype]}
        >
         {children}
        </Animated.View>
    

    When you try to render it or remove it from UI it will show you a fade-out animation. You can get inspired by it to improve your exact desire.