Anthony Tietjen
Anthony Tietjen

Reputation: 1064

Cross-platform React Native file structure

I'm coming from Ionic 2 where I write my code once, and it runs everywhere.

According to this page https://facebook.github.io/react-native/docs/platform-specific-code.html "When building a cross-platform app, you'll want to re-use as much code as possible."

How can I "reuse" code across iOS and Android in ReactNative? In the starter app I see two files: index.ios.js and index.android.js. Is there something like index.js that I can use for sharing across platforms?

It seems like there should be one file for shareable code, since that web page mentioned above also shows how you can use the Platform module to check what OS you are on.

I realize that sometimes you need different behavior on different platforms, but, assuming that my app is simple enough, and my code ends up exactly the same on both platforms, do I have to copy/paste from one to the other? How can I pull same-functionality into it’s own file to be shared on both platforms?

What am I missing?

Thanks!

Upvotes: 3

Views: 1468

Answers (1)

Tushar Khatiwada
Tushar Khatiwada

Reputation: 2027

Here's what you can do. Create a file say main.js that will act as your root page.

main.js

import React, { Component } from 'react';
import { Text } from 'react-native';

export default class Main extends Component {
  render() {
    return (
      <Text>Hello world! from both IOS and Android</Text>
    );
  }
}

Now on your index.android.js and index.ios.js import that main file and register your Main component as root using AppRegistry.

index.android.js and index.ios.js

import React from 'react';
import {
  AppRegistry
} from 'react-native';
import Main from './main';

AppRegistry.registerComponent('DemoApp', () => Main);

if you run react-native run-android and react-native run-ios the Main component will be rendered for both the platforms.

All of the Components with No IOS and Android suffix works for both platforms. Like Navigator works for both ios and android but NavigatorIOS works only for ios. So you'll have to make sure that you're using the cross platform components.

If you need to use platform specific components, then you can use platform detection login to do so:

import { Platform } from 'react-native';
if(Platform.OS === 'ios').....

or

if(Platform.OS === 'android')...

Upvotes: 8

Related Questions