React Native: How to split a file up into multiple files and import them?
Asked Answered
G

2

22

I am writing my first app in react native and my js file is getting pretty big. What is the proper way to split the file up.

If i have something like

var MyClass = React.createClass({
  ...
})

Can I save it at myclass.js and include in by some command in another js file?

Gerfalcon answered 3/10, 2015 at 14:17 Comment(0)
A
17

In general you can do the following:

var MyClass = React.createClass({
    ...
)}

module.exports = MyClass;

This way you tell what should be publicly available.

And then, in your former big file you can load the contents like this:

var MyClass = require('./myclass.js');

Require returns the object that references the value of module.exports.

Autograft answered 3/10, 2015 at 19:48 Comment(2)
nice, thanks. Is it also possible to export more than one class?Gerfalcon
I believe so. Assign MyClass to module.exports.MyClass then import it by calling require('./MyClass.js').MyClass You will have to do this for each class you assign to exports.Bugle
L
18

Here is the updated solution with using the import statement (in latest React-Native and generally Javascript adhering to ECMAScript6 and later):

file1 myClass.js:

export default class myClass {...}

file2 app.js:

import myClass from './myClass';

This is the basic version using a single default export. You can also export named exports that have to be explicitly listed on import. For more info see export and import.

Lelahleland answered 15/4, 2017 at 8:39 Comment(1)
the ./ (dot-slash) when importing is important when importing a local file, it fixed my problem. ThanksTourmaline
A
17

In general you can do the following:

var MyClass = React.createClass({
    ...
)}

module.exports = MyClass;

This way you tell what should be publicly available.

And then, in your former big file you can load the contents like this:

var MyClass = require('./myclass.js');

Require returns the object that references the value of module.exports.

Autograft answered 3/10, 2015 at 19:48 Comment(2)
nice, thanks. Is it also possible to export more than one class?Gerfalcon
I believe so. Assign MyClass to module.exports.MyClass then import it by calling require('./MyClass.js').MyClass You will have to do this for each class you assign to exports.Bugle

© 2022 - 2024 — McMap. All rights reserved.