Skip to content

Commit

Permalink
docs(react-navigation): throw handle existsScreen
Browse files Browse the repository at this point in the history
  • Loading branch information
gronxb authored Aug 27, 2024
1 parent 2ffe95f commit 3180366
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions docs/example/react-navigation.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@ Example: [react-navigation](https://github.com/gronxb/webview-bridge/tree/main/e

## React Native Part

```tsx
// This file is src/navigation.ts

import type { NativeStackScreenProps } from '@react-navigation/native-stack';

export type RootStackParamList = {
Home: undefined;
Profile: { userId: string };
Feed: { sort: 'latest' | 'top' } | undefined;
};
```

```tsx
// This file is src/bridge.ts

Expand All @@ -21,6 +33,15 @@ import { RootStackParamList } from "./navigation";

export const navigationRef = createNavigationContainerRef<RootStackParamList>();

const existsScreen = (name: string): boolean => {
return Boolean(
navigationRef.current?.isReady() &&
navigationRef.current
.getState()
.routeNames.find((routeName) => routeName === name),
);
};

export const appBridge = bridge({
async getMessage() {
return "I'm from native" as const;
Expand All @@ -45,6 +66,9 @@ export const appBridge = bridge({
params: RootStackParamList[RouteName],
) {
if (navigationRef.current?.isReady()) {
if (!existsScreen(name)) {
throw new Error(`Screen ${name} not found`);
}
navigationRef.current.navigate(name as any, params as any);
}
},
Expand All @@ -53,6 +77,9 @@ export const appBridge = bridge({
params: RootStackParamList[RouteName],
) {
if (navigationRef.current?.isReady()) {
if (!existsScreen(name)) {
throw new Error(`Screen ${name} not found`);
}
navigationRef.current.dispatch(StackActions.push(name, params));
}
},
Expand All @@ -61,6 +88,9 @@ export const appBridge = bridge({
params: RootStackParamList[RouteName],
) {
if (navigationRef.current?.isReady()) {
if (!existsScreen(name)) {
throw new Error(`Screen ${name} not found`);
}
navigationRef.current.dispatch(StackActions.replace(name, params));
}
},
Expand Down

0 comments on commit 3180366

Please sign in to comment.