Googling
Googling

Reputation: 3

how can i wrap react navigation with context

i'm new in react-native and i try to wrap react navigation with context i see some code wrap with createAppContainer but it is react-navigation v4. i try to use some new code but i got error how can i fix it.

The error I'm getting is:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports

Here is my implementation:

Context.js

import React from 'react'

const Context = React.createContext();

export const Provider = ({children})=>{
    return(
        <Context.Provider>
            {children}
        </Context.Provider>
    )
}

App.js

import React, { Component } from 'react'
import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
import { IndexScreen } from './src/screens';
import Provider from './src/contexts/Context';

const Stack = createStackNavigator();

class App extends Component {
  render(){ 
    return(
      <NavigationContainer>
        <Stack.Navigator initialRouteName = "Index">
        <Stack.Screen name = "Index" component = {IndexScreen}/>
        </Stack.Navigator>
      </NavigationContainer>
    )
  }
}

export default  () => {
  return ( 
    <Provider>
    <App />
    </Provider>
  )
}

thanks.

Upvotes: 0

Views: 4836

Answers (1)

Moistbobo
Moistbobo

Reputation: 2962

Since Provider is a named export from Context.js, it should be imported like so:

import {Provider} from './src/contexts/Context

Importing it like you are now assumes that it is a default export from Context.js, which it is not.

After this, I would recommend changing App.js so that you're not creating a separate default export just to wrap the App in the Provider by changing the App to something like this:

export default class App extends Component {
  render() {
    return (
      <Provider>
        <NavigationContainer>
          <Stack.Navigator initialRouteName="Index">
            <Stack.Screen name="Index" component={() => (
              <View>
                <Text>Hello world</Text>
              </View>
            )} />
          </Stack.Navigator>
        </NavigationContainer>
      </Provider>
    )
  }
}

Here is a snack with those changes.

Upvotes: 1

Related Questions