Skip to content

Commit

Permalink
fix(readiumview): fix an issue when no forwardRef is passed on Android
Browse files Browse the repository at this point in the history
  • Loading branch information
jspizziri committed Jul 29, 2024
1 parent bdddc69 commit bbc1967
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions src/components/ReadiumView.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useCallback, useState, useEffect, forwardRef } from 'react';
import React, { useCallback, useState, useEffect, forwardRef, ForwardedRef, useRef, createRef } from 'react';
import { View, Platform, findNodeHandle, StyleSheet } from 'react-native';

import type { BaseReadiumViewProps, Dimensions } from '../interfaces';
Expand All @@ -13,18 +13,21 @@ export const ReadiumView: React.FC<ReadiumProps> = forwardRef(({
onTableOfContents: wrappedOnTableOfContents,
settings: unmappedSettings,
...props
}, ref) => {
}, forwardedRef) => {
const defaultRef = useRef<any>(null);
const [{ height, width }, setDimensions] = useState<Dimensions>({
width: 0,
height: 0,
});

// set the view dimensions on layout
const onLayout = useCallback(({ nativeEvent: { layout: { width, height } }}: any) => {
setDimensions({
width: dimension(width),
height: dimension(height),
});
}, []);

// wrap the native onLocationChange and extract the raw event value
const onLocationChange = useCallback((event: any) => {
if (wrappedOnLocationChange) {
Expand All @@ -39,13 +42,22 @@ export const ReadiumView: React.FC<ReadiumProps> = forwardRef(({
}
}, [wrappedOnTableOfContents]);

// create the view fragment on android
useEffect(() => {
if (Platform.OS === 'android') {
// @ts-ignore
const viewId = findNodeHandle(ref.current);
if (Platform.OS === 'android' && defaultRef.current) {
const viewId = findNodeHandle(defaultRef.current);
createFragment(viewId);
}
}, [])
}, []);

// assign the forwarded ref
useEffect(() => {
if (forwardedRef && 'current' in forwardedRef) {
forwardedRef.current = defaultRef.current;
} else if (forwardedRef) {
forwardedRef(defaultRef);
}
}, [defaultRef.current !== null])

return (
<View
Expand All @@ -59,7 +71,7 @@ export const ReadiumView: React.FC<ReadiumProps> = forwardRef(({
onLocationChange={onLocationChange}
onTableOfContents={onTableOfContents}
settings={unmappedSettings ? Settings.map(unmappedSettings) : undefined}
ref={ref}
ref={defaultRef}
/>
</View>
);
Expand Down

0 comments on commit bbc1967

Please sign in to comment.