callbackreact-nativeconditional-renderingreact-native-modal

Custom callBack on a Modal with conditional rendering


I am building a ride sharing app to learn react-native. In order to publish a new Ride, I have a Modal which renders conditionaly on the step state and each step has a diferente UI. Like:

let screen;
if (step===1){
        ecraStep=<Screen1/>
} if (step===2){
        ecraStep=<Screen2/>
} ...

On step=1 (which is the initial value) I want the callBack button to close the Modal and whenever step>1 I want it to call the following function:

function togglePreviousStep() {
   setStep(step-1);
};

Which is essentially going back to the last rendered screen. I have tried it by writting this inside the Modal function component:

useFocusEffect(
        React.useCallback(() => {
          const onBackPress = () => {
            if (step>1) {
              togglePreviousStep();
              return true;
            } else if (step===1) {
                props.closeModal();
              return false;
            }
          };
          BackHandler.addEventListener('hardwareBackPress', onBackPress);
          return () =>
            BackHandler.removeEventListener('hardwareBackPress', onBackPress);
        }, [step, togglePreviousStep])
      );

However, no matter the step state, whenever I press the backButton it closes the Modal. I don't understand what I am doing wrong.

EDITED

I implemented the Modal from react-native-modal. I used the prop onBackButtonPress like this:

<Modal 
        onBackButtonPress={props.onBackButtonPress} 
        visible={showModal} 
        //...
        >
                    <NewRidesModal
                        //...
                        />
                </Modal>

And inside the Modal Screen I wrote:

if (step===1) {
        onBackPressButton=(() => props.closeModal());
    } else if (step>1){
        onBackPressButton=(() => togglePreviousStep())
    }

However, it still closes the modal when I press the android back button...


Solution

  • The onBackBackButtonPress is actually deprecated or removed.

    Later on, I read a bit more about the modal documents on https://reactnative.dev/docs/modal#onrequestclose and I found out that:

    The onRequestClose callback is called when the user taps the hardware back button on Android or the menu button on Apple TV.

    I should have investigated this before making this question. All I needed can be done with the onRequestClose prop like the following:

    <Modal 
        onRequestClose={() => {
          if (step===1) {
            toggleModal();
        } else if (step>1 && step<8){
            togglePreviousStep(); 
        }
        }}
    >
        //...
    </Modal>