Cross-platform responsive Native file structure

I am coming from Ionic 2 where I write my code once and it works everywhere.

According to this page https://facebook.github.io/react-native/docs/platform-specific-code.html "When building a cross-platform application, you will want to reuse as much code as possible."

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

There seems to be one file for common code, as the above webpage also shows how you can use a platform module to check what OS you are on.

I understand that sometimes you want different behavior on different platforms, but assuming that my application is simple enough and my code ends up on both platforms in exactly the same way, do I need to copy / paste them from one to the other? How can I use the same functionality in my own file to be shared across both platforms?

What am I missing?

Thank!

+2


source to share


1 answer


Here's what you can do. Create a file: main.js to 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 index.android.js and index.ios.js, import this 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 displayed for both platforms.

All components are suffixed with None IOS

and Android

work for both platforms. Navigator

Works similarly for both ios and android, but NavigatorIOS

only works for ios. Therefore, you will need to make sure you are using cross platform components.

If you need to use platform specific components, you can use the platform registration id to do this:

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

      

or

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

      

+6


source







All Articles