Search code examples
react-nativereact-navigationreact-navigation-v5react-navigation-stack

Cannot create custom StackNavigator - "Couldn't register the navigator"?


I'm trying to create a custom StackNavigator and distribute it on a custom package. The problem is that when I want to apply my custom Stack I get the following error:

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

This is my App.tsx:

import { createThemedStack } from '@my-custom-package' 

//this is the reference to my custom navigator
const ThemedStack = createThemedStack()

function App() {
  return (
    <NavigationContainer>
      <ThemedStack.Navigator>
        <ThemedStack.Screen name='Screen 1' component={Screen1} />
        <ThemedStack.Screen name='Screen 2' component={Screen2} />
        ...
      </ThemedStack.Navigator>
    </NavigationContainer>
  )
}

export default App

ThemedStack.tsx - Here I want to apply some custom common styles to the stacks:

import * as React from 'react'
import { useNavigationBuilder, createNavigatorFactory, StackRouter } from '@react-navigation/native'
import { StackView } from '@react-navigation/stack'
// @ts-ignore
function ThemedStack({ initialRouteName, children, screenOptions, ...rest }) {
  const { state, descriptors, navigation } = useNavigationBuilder(StackRouter, {
    initialRouteName,
    children,
    screenOptions,
  })

  return <StackView {...rest} state={state} navigation={navigation} descriptors={descriptors} />
}

export default createNavigatorFactory(ThemedStack)

What am I doing wrong? I dont get it. The ThemedStack navigator is inside a NavigationContainer.

I did this based on https://reactnavigation.org/docs/custom-navigators/ RN Navigation docs, although they don't say anything about doing it in external package structure.

Thanks in advance :)


Solution

  • Sounds like you have @react-navigation/native in dependencies in your package which results in multiple versions installed. You should move it to peerDependencies.