react-native: Issue when displaying a modal after dismissing another modal

Description

Before RN 0.76.5, on iOS it was possible to show a modal and after dismissing it, showing another one. Now, when doing the exact same thing on the old architecture the second modal is not showing up. https://github.com/facebook/react-native/issues/47694 https://github.com/facebook/react-native/issues/48245 https://github.com/facebook/react-native/issues/48559

The error is not happening on new architecture

Steps to reproduce

  1. Create two different modals
  2. Show the first one by clicking on a button
  3. Then, create a button that will dismiss the first modal and display the second one
  4. The second one won’t show up

React Native Version

0.76.5

Affected Platforms

Runtime - iOS

Output of npx react-native info

System:
  OS: macOS 15.2
  CPU: (10) arm64 Apple M1 Max
  Memory: 482.95 MB / 32.00 GB
  Shell:
    version: "5.9"
    path: /bin/zsh
Binaries:
  Node:
    version: 22.12.0
    path: ~/.nvm/versions/node/v22.12.0/bin/node
  Yarn: Not Found
  npm:
    version: 8.19.4
    path: ~/code/yonitou/hygo/node_modules/.bin/npm
  Watchman: Not Found
Managers:
  CocoaPods:
    version: 1.11.2
    path: /Users/yonitouboul/.rbenv/shims/pod
SDKs:
  iOS SDK:
    Platforms:
      - DriverKit 24.2
      - iOS 18.2
      - macOS 15.2
      - tvOS 18.2
      - visionOS 2.2
      - watchOS 11.2
  Android SDK: Not Found
IDEs:
  Android Studio: 2024.1 AI-241.18034.62.2411.12071903
  Xcode:
    version: 16.2/16C5032a
    path: /usr/bin/xcodebuild
Languages:
  Java:
    version: 17.0.1
    path: /usr/bin/javac
  Ruby:
    version: 2.7.4
    path: /Users/yonitouboul/.rbenv/shims/ruby
npmPackages:
  "@react-native-community/cli": Not Found
  react: Not Found
  react-native: Not Found
  react-native-macos: Not Found
npmGlobalPackages:
  "*react-native*": Not Found
Android:
  hermesEnabled: Not found
  newArchEnabled: Not found
iOS:
  hermesEnabled: Not found
  newArchEnabled: Not found


### Stacktrace or Logs

```text
No errors logs

Reproducer

https://github.com/yonitou/modal-bug

Screenshots and Videos

When I click on the button “Close modal”, it should dismiss the red one and show the blue one but the blue one never shows. You will notice that if enabling new architecture, the problem disappears https://github.com/user-attachments/assets/72aca692-d90d-40f7-b500-ef574ae26658

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 14
  • Comments: 30 (7 by maintainers)

Most upvoted comments

Hi 😃 Can we have some news ? Thanks again !

Workaround I found here is to use the onDismiss callback from the first modal to re-render the second modal by resetting it’s key

<Modal
     key={"modal_one"}
     onDismiss={() => {
           setUpdateKey(updateKey + 1);
     }}
...
<Modal
     key={"modal_two" + updateKey}

You can put both into a container and reset the key of the container if the order of the modals is undetermined

Seems like this might be related to #49717

I’m also getting some very weird behavior when interacting with multiple <Modal/>'s on the new architecture in 0.76.7.

From reading the threads: It appears stacked/quickly dismissed and shown <Modal/> components in the new architecture are very fragile and may have been fixed in 0.76.5 but might have been broken again in 0.76.7.

I know you guys are very busy, so if I have time I’ll try to create another repro (maybe a separate issue), but Modal’s are so prevalent I wouldn’t be surprised if more people start joining in on these threads, might be a good place to invest some time.

I can’t because I’m using react-native-maps which is not compatible with new architecture (yet) (we can see it on react native directory and on the repo itself) It’s the only package we are having that is not compatible. But believe me, I’m just waiting to opt-in to new architecture 😃

Slightly different reproduction. This works in 0.75.5, and does not in 0.76.0 (both on old architecture).

If you set animationType="none", it seems to work correctly on both versions.

Using setTimeout(() => setXVisible(true), 500) works some of the time because the slide animation is 500ms.

So it seems like you can no longer open a second modal whilst you have a first one still open, and a modal doesn’t “close” until the animation finishes (explaining the animation/setTimeout).

import { Button, Modal, Text, View } from "react-native";
import { useState } from "react";

export const App = (): JSX.Element => {
  const [aVisible, setAVisible] = useState(true);
  const [bVisible, setBVisible] = useState(false);

  return (
    <View>
      <Modal visible={aVisible} animationType="slide">
        <View style={{ flex: 1, margin: 100 }}>
          <Text>A</Text>
          <Button
            title="Close"
            onPress={() => {
              setAVisible(false);
              setBVisible(true);
            }}
          />
        </View>
      </Modal>
      <Modal visible={bVisible} animationType="slide">
        <View style={{ flex: 1, margin: 100 }}>
          <Text>B</Text>
          <Button
            title="Close"
            onPress={() => {
              setBVisible(false);
              setAVisible(true);
            }}
          />
        </View>
      </Modal>
    </View>
  );
};

export default App;

It’s caused by the changes from this commit (included in 0.76.0).

If you apply that patch on top of 0.75.5, it causes this issue.

Whilst the commit was reverted a few days later, you can see it is only reverted in 0.77+. 0.76.X still has the change.

You can apply this diff in react-native 0.76.X with patch-package to work around it until 0.77+.

diff --git a/node_modules/react-native/React/Views/RCTModalHostViewManager.m b/node_modules/react-native/React/Views/RCTModalHostViewManager.m
index 8407662..eccf05f 100644
--- a/node_modules/react-native/React/Views/RCTModalHostViewManager.m
+++ b/node_modules/react-native/React/Views/RCTModalHostViewManager.m
@@ -64,9 +64,9 @@ RCT_EXPORT_MODULE()
     if (self->_presentationBlock) {
       self->_presentationBlock([modalHostView reactViewController], viewController, animated, completionBlock);
     } else {
-      [[self _topMostViewControllerFrom:[modalHostView reactViewController]] presentViewController:viewController
-                                                                                          animated:animated
-                                                                                        completion:completionBlock];
+      [[modalHostView reactViewController] presentViewController:viewController
+                                                        animated:animated
+                                                      completion:completionBlock];
     }
   });
 }
@@ -107,26 +107,6 @@ RCT_EXPORT_MODULE()
   _hostViews = nil;
 }
 
-#pragma mark - Private
-
-- (UIViewController *)_topMostViewControllerFrom:(UIViewController *)rootViewController
-{
-  UIViewController *topController = rootViewController;
-  while (topController.presentedViewController) {
-    topController = topController.presentedViewController;
-  }
-  if ([topController isKindOfClass:[UINavigationController class]]) {
-    UINavigationController *navigationController = (UINavigationController *)topController;
-    topController = navigationController.visibleViewController;
-    return [self _topMostViewControllerFrom:topController];
-  } else if ([topController isKindOfClass:[UITabBarController class]]) {
-    UITabBarController *tabBarController = (UITabBarController *)topController;
-    topController = tabBarController.selectedViewController;
-    return [self _topMostViewControllerFrom:topController];
-  }
-  return topController;
-}
-
 RCT_EXPORT_VIEW_PROPERTY(animationType, NSString)
 RCT_EXPORT_VIEW_PROPERTY(presentationStyle, UIModalPresentationStyle)
 RCT_EXPORT_VIEW_PROPERTY(transparent, BOOL)

Spent about two days thinking I went crazy but lo and behold, this is a known issue. My current project uses modals extensively and I am really disappointed with the effort from the team here. Too many products out there rely on libraries that are nowhere near ready for new-arch rollover to just let this ride. Really bummed by this.

Do we know in which version this has regressed? Was it behaving correctly in 0.75?

Hi, @cortinico – This was working fine in 0.75.4. It breaks if you upgrade to 0.76.7.

Personally, I was able to work around the issue by introducing a 100ms setTimeout between dismissing the first modal and displaying the second but I realize that may be difficult for some.

is it possible to know when that will be fixed ?

I’m sorry but we don’t share ETAs on when a bug will be fixed because our team is so small, and we receive hundreds of bugs/issue-report.

Currently we’re focusing on New Architecture bugs so this has lower priority sadly.

If useful (in case this issue is ‘upvotable’) - we are in the same situation: this issue affects our app, and we are not in a position to migrate to the New Architecture as we have a few dependencies not yet supporting it

Yes but even if it’s the case, our app is quite big and we have more than 50k users. When I’ll switch to the new architecture, I will need to make some tests, check that everything works well, it’ll be a breaking change. Right now, we just need to release some fixes to our users and we are stuck because of this issue. We really need it to be fixed please 🙏

I can’t because I’m using react-native-maps which is not compatible with new architecture (yet) (we can see it on react native directory and on the repo itself) It’s the only package we are having that is not compatible. But believe me, I’m just waiting to opt-in to new architecture 😃

Thanks for the insights 👍 Super valuable for us

Updated my app to expo 52 and 0.76.7 react native. Tried using new arch but expo camera was crashing when scanning barcode.

There was a bug where a modal would not render I tracked it down due to this issue so thank you. Here is what happens for me. Not that adding a timeout fixes the issue.

Below is a minimal example that reproduces the bug. In this example, we conditionally render one of two modals based on a state value. Switching between the modals sometimes results in the second modal (Modal B) not appearing as expected:

import React, { useState } from 'react';
import { View, Modal, Text, Button } from 'react-native';

const MinimalModalBug = () => {
  const [modalType, setModalType] = useState(null);

  return (
    <View style={{ marginTop: 50, alignItems: 'center' }}>
      <Button title="Show Modal A" onPress={() => setModalType('A')} />
      <Button title="Show Modal B" onPress={() => setModalType('B')} />

      {modalType === 'A' && (
        <Modal
          visible={true}
          transparent
          onRequestClose={() => setModalType(null)}
        >
          <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#00000066' }}>
            <Text>Modal A</Text>
            <Button title="Close" onPress={() => setModalType(null)} />
          </View>
        </Modal>
      )}

      {modalType === 'B' && (
        <Modal
          visible={true}
          transparent
          onRequestClose={() => setModalType(null)}
        >
          <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#00000066' }}>
            <Text>Modal B</Text>
            <Button title="Close" onPress={() => setModalType(null)} />
          </View>
        </Modal>
      )}
    </View>
  );
};

export default MinimalModalBug;

Explanation

  • State Control: The modalType state variable is used to determine which modal to show: 'A' or 'B'.
  • Conditional Rendering: Two modals are rendered conditionally. When modalType is 'A', Modal A appears; when it’s 'B', Modal B appears.
  • Bug Manifestation: Due to a bug in React Native’s Modal component, toggling to show Modal B after Modal A can sometimes cause Modal B not to render correctly.

This minimal reproduction code highlights the issue in a straightforward manner.

I’m running RN 0.76.7 with new arch enabled (the issue is not happening to me with old arch) and solved it by creating a shared stack of modals only for iOS.

With this patch you can encapsulate this modification in a separate file and more important is making sure the most recent modal will be displayed but will also close any open Modal before to prevent frozen screens or any unexpected issue.

Additionally, also works when you are controlling Modals from differents sides of your application and you don’t have an easy way to manually dismiss one before displaying the new one.

IOSModalStackProvider.tsx

import type { ReactNode } from 'react';

import React, { createContext, useCallback, useContext, useMemo, useState } from 'react';

interface ModalStackContextProps {
	stack: string[];
	open: (id: string) => void;
	close: (id: string) => void;
	clear: () => void;
}

const ModalStackContext = createContext<ModalStackContextProps | undefined>(undefined);

export const useModalStack = () => {
	const context = useContext(ModalStackContext);
	if (!context) {
		throw new Error('useModalStack must be used within a ModalStackProvider');
	}
	return context;
};

interface ModalStackProviderProps {
	children: ReactNode;
}

export const ModalStackProvider: React.FC<ModalStackProviderProps> = ({ children }) => {
	const [stack, setStack] = useState<string[]>([]);

	const open = useCallback((id: string) => {
		setStack(prevStack => {
			return [...prevStack, id];
		});
	}, []);

	const close = useCallback((id: string) => {
		setStack(prevStack => prevStack.filter(modalId => modalId !== id));
	}, []);

	const clear = useCallback(() => {
		setStack([]);
	}, []);

	const contextValue = useMemo(
		() => ({
			stack,
			open,
			close,
			clear,
		}),
		[stack, open, close, clear],
	);

	return <ModalStackContext.Provider value={contextValue}>{children}</ModalStackContext.Provider>;
};

Modal.tsx

import { Modal as NativeModal } from 'react-native';

....

export const IOSModal = function Modal(props: { visible?: boolean }) {
	const { visible: propsVisible = true, ...otherProps } = props;
	const [visible, setVisible] = useState(propsVisible);
	const [closing, setClosing] = useState(false);

	const id = useMemo(() => `modal-${new Date().getTime()}`, []);

	const { open, close, stack } = useModalStack();

	useEffect(() => {
		if (visible !== propsVisible) {
			setClosing(!propsVisible);
			setVisible(propsVisible);
		}
	}, [propsVisible, visible]);

	useEffect(() => {
		if (!visible && closing) {
			close(id);
		} else if (visible) {
			open(id);
		}
	}, [visible, closing, id, open, close]);

	useEffect(() => {
		return () => {
			if (closing) {
				close(id);
			}
		};
	}, [id, closing, close]);

	const isVisible = stack[stack.length - 1] === id;

	return (
		<NativeModal
			visible={isVisible}
			transparent
			animationType='none'
			{...otherProps}
		/>
	);
};

export const Modal = isIOS() ? IOSModal : NativeModal;

For some weird reason before landing into this solution when changing the Modal transparency between false and true to show that solid background there were no issues on my end, like if the view hierarchy with transparent={false} was formed differently and not causing the issue.

Well hope it helps or at least to give an idea on how to patch this on your end.

Please @cortinico, is it possible to know when that will be fixed ? Since the day I wrote my issue, we didn’t release our app because of this bug. Our app is in the top 30 weather app in France, this issue is really compromising us right now 😕

The error is not happening on new architecture

Out of curiosity, what’s the reason you can’t use the old architecture?

Asking as, in the future we’ll be dropping support for old arch. So yes, we can look into fixing this, but you should consider using new arch, especially if this behavior is already fixed.