how to finish modal animation in react-native-modal componentwillunmount?

2.1k Views Asked by At

I am looking for a solution to delay RN component unmount until react-native-modal animationOut is completed. This animation is triggered by setting isVisible=false. With my current implementation the animation performs as expected on componentWillMount hook, however the problem is in componentWillUnmount the alert unmounts without an animation. I suspect this is because the component unmounts before the animation even has a change to start. Here's the alert component:

//modal component
import Modal from "react-native-modal";

export default CustomAlert = props => {

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

    useEffect(() => {
        setIsVisible(true)
        return () => setIsVisible(false);
    }, [])

    return (
        <Modal
            isVisible={isVisible}
            animationIn={'slideInUp'}
            animationOut={'slideOutDown'}
        >
            <View
               ...
            </View>
        </Modal>
    )
};

Here's how the custom alert needs to be used:

export default ApplicationScreen = ({ navigation }) => {

    const [alert, setAlert] = useState(null);

    ...
    const doSomething = () => {
        ...
        //show alert
        setAlert({ title: 'title', message: 'message'});
        ...
        //hide alert
        setAlert(null);
        ...
    }
    ...

    return (
        <SafeAreaView style={styles.container}>

            {alert &&
                <CustomAlert
                    title={alert?.title}
                    message={alert?.message}
                    ...
                />
            }
            ...
        </SafeAreaView>
    )
}
1

There are 1 best solutions below

0
On

The problem is that you are containing the CustomAlert in a conditional rendering. Once the alert is set to false, the Modal would dismount directly. You could pass the alert state into CustomAlert as property and then into Modal. The 's property isVisible would hanlde the render of the modal for you with animation.

ApplicationScreen:

<SafeAreaView style={styles.container}>
  <CustomAlert
    title={alert?.title}
    message={alert?.message}
    isAlertVisible={alert? true : false}
  />
</SafeAreaView>

in CustomAlert:

return (
        <Modal
            isVisible={props.isAlertVisible}
            animationIn={'slideInUp'}
            animationOut={'slideOutDown'}
        >
            <View
               ...
            </View>
        </Modal>
    )