When building a package containing a stack navigator in React-Native, how should I handle my dependencies?

Viewed 23

Like the title says, I'm building packages that a actually some app features.

So those features contain their own stack navigators, including screens.

Here's what I've got so far:

The Home feature (which is a package):

import React from 'react';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { HomeView } from '../src/views';

const RootStack = createNativeStackNavigator<any>();
const HomeModule = () => {
  return (
    <RootStack.Navigator initialRouteName='Home'>
      <RootStack.Screen name="Home" component={HomeView} />
    </RootStack.Navigator>
  );
};

export default HomeModule;

package.json from the library (I removed the irrelevant stuffs for readability) :

"dependencies": {
    "@react-navigation/native": "^6.0.11",
    "@react-navigation/native-stack": "^6.7.0",
    "react-native-safe-area-context": "^4.3.1",
    "react-native-screens": "^3.15.0"
  },
  "devDependencies": {},
  "resolutions": {
    "@types/react": "18.0.0"
  },
  "peerDependencies": {
    "react": "18.0.0",
    "react-native": "0.69.1"
  },

The RN host app :

import { NavigationContainer } from '@react-navigation/native';
import * as React from 'react';
import { HomeModule } from '@compagny-name/features-library';

export default function App() {
  return (
    <NavigationContainer>
      <HomeModule />
    </NavigationContainer>
  );
}

package.json :

 "dependencies": {
    "react": "17.0.2",
    "react-native": "0.68.2",
    "@react-navigation/native": "^6.0.11",
    "@react-navigation/native-stack": "^6.7.0",
    "react-native-safe-area-context": "^4.3.1",
    "react-native-screens": "^3.15.0"

  },

After installing the library and importing the feature, the app crash and throws an error :

 ERROR  Error: Couldn't register the navigator. Have you wrapped your app with 'NavigationContainer'?

This can also happen if there are multiple copies of '@react-navigation' packages installed.

I'm not sure how to handle dependencies in that use case.

Any help ?

1 Answers

In the library project, the @react-navigation/native-stack dependency should be handled just like react and react-native dependencies.

So the package.json should look like that:

  "devDependencies": {
    "react": "18.0.0",
    "react-native": "0.69.1",
    "@react-navigation/native-stack": "^6.7.0",
  },
  "peerDependencies": {
    "react": "18.0.0",
    "react-native": "0.69.1",
    "@react-navigation/native-stack": "^6.7.0",
  },
Related