Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-platform React Native file structure

Tags:

react-native

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!

like image 692
Anthony Tietjen Avatar asked Jul 18 '26 17:07

Anthony Tietjen


1 Answers

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')...
like image 125
Tushar Khatiwada Avatar answered Jul 20 '26 11:07

Tushar Khatiwada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!