1

I'm trying to organize my common theme folder in React Native. But found a problem when trying to default export a module in a different file. Basically, trying to do this basic structure:

+-- components
+-- theme
|  +-- appStyles.js
|  +-- colors.js
|  +-- index.js

In theme/appStyles.js would export default a single object (same for colors.js):

export default {
  screen: {
    flex: 1,
  },
};

In theme/index.js looks like this where it'll export default an object, mapping the files in the theme folder:

import AppStyles from './appStyles';
import Colors from './colors';

export default {
  AppStyles,
  Colors,
};

When I'm trying to use this in another module, i.e. SomeComponent.js, it would just be undefined and would be unusable:

import { AppStyles } from '../theme';

console.log(AppStyles); // would log 'undefined'

As a work around, I've been doing:

In theme/appStyles.js:

export const AppStyles = {
  screen: {
    flex: 1,
  },
};

In theme/index.js:

export * from './appStyles';

It would then be usable in SomeComponent.js:

import { AppStyles } from '../theme';

console.log(AppStyles); // would log Object structure

Been using this 'pattern' in ReactJS Web. Just wondering how does React Native handle this module resolution.

1 Answer 1

1

No need to wrap default export by {}

import AppStyles from './appStyles';

export default AppStyles;

Than simply import with whatever name you want

import  AppStyles  from '../theme';

console.log(AppStyles);

I have multiple things to be exported from index

import  AppStyles  from '../theme';
import  Color from '../color';
export{
  Appstyle as default,
  Color
}

Than simply import as

import  AppStyles, {Color}  from '../theme';

console.log(AppStyles);
console.log(Color);
Sign up to request clarification or add additional context in comments.

3 Comments

There are other files that could be in the theme folder like colors.js, fonts.js. And then would want to be exported from the index.js file as { Colors, Fonts, AppStyles }.
@Ardemenial ../theme will always point to index.js, if you want to club all the files exported values in single file, you can use named export in index and then import with name
Got it! Had a re-read from the docs. Thought it was react-native specific, since I was encountering some issues with the bundler before. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.