Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly import/export components in React Native?

I'm trying to export initial component, but all the time I'm getting Invariant Violation error:

Is there any better way to export my HMAPP component and import it inside App.js?

Error image: Error screen

Here is my App.js:

import HMAPP from './app/HMAPP';

export default HMAPP;

Here is my HMAPP component:

 import { Provider } from 'react-redux';
import { persistStore } from 'redux-persist';
import { Navigation } from 'react-native-navigation';
import Mapbox from '@mapbox/react-native-mapbox-gl';

import { registerScreens } from './screens';
import store from './store/configureStore';
import { appInit, getInitialScreen } from './appInit';
import { handleErrorObject } from './lib/handleError';

Mapbox.setAccessToken('pkaeda324234');

const persistor = persistStore(
    store,
    null,
    () => {
        registerScreens(store, Provider);

        appInit(store)
            .then(() => {
                const initialScreen = getInitialScreen(store.getState());

                Navigation.startSingleScreenApp({
                    screen: {
                        screen: initialScreen,
                    },
                    passProps: {
                        persistor,
                    },
                    drawer: {
                        left: {
                            screen: 'DrawerMenuScreen',
                        },
                    },
                    appStyle: {
                        orientation: 'portrait',
                    },
                });
            })
            .catch((error) => {
                handleErrorObject('Error initializing app', error);
            });
    },
);
like image 278
SAdnan Avatar asked Dec 01 '25 22:12

SAdnan


1 Answers

According to the docs of export and import, to externalize something inside one .js file, you need to use export. Once your module is exported, you can import him and use anywhere you want inside another .js files, for example.

So, in your HMAP.js file you'll need to export your const like this:

const persistor = persistStore( ... )
export default persistor;

and if you want to export more than one, you can export an object like this:

const persistor = persistStore( ... )
const persistor2 = persistStore2( ... )
export { persistor, persistor2 };

With your content exported, you can import it now on your App.js file:

import persistor from './app/HMAPP'; // use it when you exported with "default"

or

import { persistor1, persistor2 } from './app/HMAPP';

you could also import everything inside that file:

import * as persistors from './app/HMAPP';

Hope it helps someway.

like image 184
Matheus Reis Avatar answered Dec 04 '25 15:12

Matheus Reis