Nomel
Nomel

Reputation: 123

React Native: Back Button Closes Modal

I'm trying to make a text open a modal when the user pressed on it and closes when they press on the back button. The modal does not open when the user clicks on the text. I tried following the solution from other questions but it doesn't work and their modal are not in a separate component.

Login.js

const [modalOpen, setModalOpen] = useState(false);
    return (
        <CustomScrollView>
            <ForgotPassword open={modalOpen}/> //Modal
            <ForgotPasswordText onPress={() => setModalOpen(true)}>Forgot Password?</ForgotPasswordText>
        </CustomScrollView>
    );

ForgotPassword.js

const ForgotPassword = ({open}) => {
    const [invisible, setInvisible] = useState({open});

    return (
        <Modal 
        statusBarTranslucent 
        transparent= {true} 
        visible={invisible} 
        animationType="fade"
        onRequestClose={() => {setInvisible(!open);}}>
            <CenteredModal>
                <ModalView>
                    <ForgotPasswordTitle>Forgot Password</ForgotPasswordTitle>
                </ModalView>
            </CenteredModal>
        </Modal>
        
    );     
}

Upvotes: 0

Views: 2424

Answers (1)

grenzbotin
grenzbotin

Reputation: 2565

Both components are mounted already. If you are changing the modalOpen state in your root component, it would not trigger the modal to be opened in the ForgotPassword component in the way it is implemented.

One solution would be to pass the modalOpen prop right away and using it in your Modal component for the visible prop. But you would need to pass your setModalOpen function from your Login component to remain the state, too.

const [modalOpen, setModalOpen] = useState(false);
    return (
        <CustomScrollView>
            <ForgotPassword open={modalOpen} setOpen={setModalOpen} /> //Modal
            <ForgotPasswordText onPress={() => setModalOpen(true)}>Forgot Password?</ForgotPasswordText>
        </CustomScrollView>
    );
const ForgotPassword = ({open, setOpen}) => (
        <Modal 
        statusBarTranslucent 
        transparent={true} 
        visible={open} 
        animationType="fade"
        onRequestClose={() => setOpen(!open)}>
            <CenteredModal>
                <ModalView>
                    <ForgotPasswordTitle>Forgot Password</ForgotPasswordTitle>
                </ModalView>
            </CenteredModal>
        </Modal>
    );

Find it working here: https://codesandbox.io/s/broken-night-lu8e96

Upvotes: 2

Related Questions