Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 397
Patrick Klitzke Avatar asked Oct 03 '15 14:10

Patrick Klitzke


People also ask

What is code splitting in react native?

Lusan Das. Code splitting is a way to split up your code from a large file into smaller code bundles. These can then be requested on demand or in parallel. Now, it isn't a new concept, but it can be tricky to understand.

How do I move data from one file to another in React?

For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component.


2 Answers

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.

like image 83
Oswin Noetzelmann Avatar answered Sep 26 '22 08:09

Oswin Noetzelmann


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.

like image 39
webwelten Avatar answered Sep 22 '22 08:09

webwelten