Handling Hardware Back Button Navigation on Android with react-native-screens

On Android, calling Navigation#goBack() or using a hardware back button to navigate back from a screen with a PSPDFKitView causes the app to crash when using react-native-screens. This is caused by a known issue in react-native-screens where it tries to redraw the view when it has already been recycled.

To address this issue, we added a destroyView() function to PSPDFKitView, which should be called before navigation happens to destroy the PDFKitView and avoid the redraw, in turn avoiding the crash.

The code snippet below shows how to intercept the back navigation and use the destroyView() function to stop the crash:

import React from 'react';
import PSPDFKitView from 'react-native-pspdfkit';
import { View } from 'react-native';

const DOCUMENT = 'file:///android_asset/report.pdf';

export default function PDFScreen({ navigation }) {
	// This holds the reference to the `PSPDFKitView`.
	const pdfRef = React.useRef();

	// Intercept the back button and destroy the `PSPDFKitView` before performing navigation.
	React.useEffect(() =>
		navigation.addListener('beforeRemove', (e) => {
			// Destroy the view before the screen is removed.
			pdfRef.current.destroyView();
		}),
	);

	return (
		<View style={{ flex: 1 }}>
			<PSPDFKitView
				ref={pdfRef}
				document={DOCUMENT}
				style={{ flex: 1 }}
			/>
		</View>
	);
}