React-native: Ability to detect iOS vs Android and load differing components?

Created on 1 Nov 2015  Â·  10Comments  Â·  Source: facebook/react-native

In case I want to just have index.js instead of index.ios.js and index.android.js.

Most of my components are all shared, with exception of react-native-facebook-login (since there is now Android support at https://github.com/lwhiteley/react-native-facebook-login/blob/master/Android.md and the require call is different).

Ran Commands Locked

Most helpful comment

Just use Platform.OS where you need a specification:

var {Platform} = React;

if (Platform.OS === 'ios')
  return (
    <SomeIOSComponent />
)
else
  return (
    <SomeAndroidComponent />
)

All 10 comments

For example, something like:

if (android)
  return (
    <SomeAndroidComponent />
  )
else
  return (
    <SomeIOSComponent />
  )

You can do require('react-native').Platform.OS === 'android' / 'ios' to do a runtime check. The packager will still bundle all requires that it statically discovers.

Just use Platform.OS where you need a specification:

var {Platform} = React;

if (Platform.OS === 'ios')
  return (
    <SomeIOSComponent />
)
else
  return (
    <SomeAndroidComponent />
)

Very cool. Can this get documented on the site? I'm finding myself being
able to write components that work both platforms so I only need one index
file.
On Nov 1, 2015 3:23 PM, "Adel Bruno Grimm" [email protected] wrote:

Just use Platform.OS where you need a specification:

var {Platform} = React;

if (Platform.OS === 'ios')
return (

)
else
return (

)

—
Reply to this email directly or view it on GitHub
https://github.com/facebook/react-native/issues/3822#issuecomment-152860567
.

Great @ide !

@facebook-github-bot answered

Closing this issue as @jsierles says the question asked has been answered. Please help us by asking questions on StackOverflow. StackOverflow is amazing for Q&A: it has a reputation system, voting, the ability to mark a question as answered. Because of the reputation system it is likely the community will see and answer your question there. This also helps us use the GitHub bug tracker for bugs only.

{ (Platform.OS === 'ios') ? [CODE] : [CODE] }

import {Platform, StyleSheet} from 'react-native';

const styles = StyleSheet.create({
  height: Platform.OS === 'ios' ? 200 : 100,
});

or

const Component = Platform.select({
  ios: () => require('ComponentIOS'),
  android: () => require('ComponentAndroid'),
})();

<Component />;
Was this page helpful?
0 / 5 - 0 ratings