Marco Disco
Marco Disco

Reputation: 565

React Native Platform how works?

I have a screen where I sould like to use two different pickers for Android and iOS using Platform. Looks like not working so I'm testing it just with a <Text> but doesn't change

  const PickerOS = () => {
    Platform.OS === 'android' ? (
      <Text>
        ANDROID
        {console.log('android')}
      </Text>
    ) : (
      <Text>
        IOS
        {console.log('ios')}
      </Text>
    );
  };

  useEffect(() => {
    PickerOS();
  }, []);

return (
    <View style={styles.container}>   
      {PickerOS()}
</View>

Where I mistake? thanks!

Upvotes: 2

Views: 1177

Answers (2)

Oktay Şenkan
Oktay Şenkan

Reputation: 54

When your platform-specific code is more complex, you should consider splitting the code out into separate files. React Native will detect when a file has a .ios. or .android. extension and load the relevant platform file when required from other components.

For example, say you have the following files in your project:

BigButton.ios.js
BigButton.android.js

You can then require the component as follows:

import BigButton from './BigButton';

React Native will automatically pick up the right file based on the running platform.

Source: https://reactnative.dev/docs/platform-specific-code

Upvotes: 3

SDushan
SDushan

Reputation: 4631

Your code works fine. But you didn't return anything.

const PickerOS = () => {
  return Platform.OS === "android" ? (
    <Text>
      ANDROID
      {console.log("android")}
    </Text>
  ) : (
    <Text>
      IOS
      {console.log("ios")}
    </Text>
  );
};

or you can try

const PickerOS = () =>
  Platform.OS === "android" ? (
    <Text>
      ANDROID
      {console.log("android")}
    </Text>
  ) : (
    <Text>
      IOS
      {console.log("ios")}
    </Text>
  );

Hope this helps you. Feel free for doubts.

Upvotes: 4

Related Questions