React native - import the whole file / split js code into several files

Basically I want to split the react-native code into several js files. I have my main 'index.ios.js' file. I moved some code (MainComponent class) to another file: './iOSCode/main.js'

How can I import the whole './iOSCode/main.js' file content into 'index.ios.js'?

I tried:

import { MainComponent as MainComponent }  from './iOSCode/main.js';

and

import MainComponent from './iOSCode/main.js';

with no luck...

I get an error:

Element type is invalid: expected a string (for built-in components) or  class/function [...] but got: undefined
intantiateReactComponent.js:70
instantiateChild   ReactChildReconciler.js:45

==========

EDIT:

As of @ Jagadish Upadhyay suggestion I was missing the export statement near MainComponent class inside './iOSCode/main.js'

Code:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ListView
} from 'react-native';

export class MainComponent extends Component {

  render() {
    return (
      <Text> abc </Text>
    );
  }
}

Upvotes: 2

Views: 3334

Answers (1)

To separate out a class you need to add the export statement and use this import format:

import { MainComponent as MainComponent }  from './iOSCode/main.js';

You can also move out styles into a separate file.

styles.js:

import {
  StyleSheet
} from 'react-native';

const styles = StyleSheet.create({

  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

module.exports = styles;

and use this import in the main js file:

import * as styles from './styles.js';

Remember to add: 'module.exports = styles;'

Upvotes: 4

Related Questions