How to use Platform.OS to elements in react native?

How to use Platform.OS to elements in react native?

You can also check via node but react-native provides some ways to check platform.

This one is recommended

 import {Platform} from react-native;
    st styles = StyleSheet.create({
      container: {
        flex: 1,
        ...Platform.select({
          ios: {
            backgroundColor: red,
          },
          android: {
            backgroundColor: blue,
          },
        }),
      },
    });

You can also use ternary expressions

 import {Platform, StyleSheet} from react-native;

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

Read this

You can use JSX prop spread and a ternary expression at the same time:

<KeyboardAwareScrollView
  {
    ...(Platform.OS === android ? 
    { 
      extraScrollHeight={100}
      enableOnAndroid={true}
      keyboardShouldPersistTaps=handled
    } : {})
  }
>

I highly recommend against doing this all inline though, since its hard to read. You could do something a bit readable (and declarative) using Platform.select:

const keyboardProps = Platform.select({
  android: { … },
  ios: {},
});
…
<KeyboardAwareScrollView {...keyboardProps}>

How to use Platform.OS to elements in react native?

If you want to keep your code much simpler and cleaner to understand, do this:
For example, if you want to specific marginTop per specific operating System. You can do this:

 <View style={{justifyContent:center,marginTop:Platform.select({
            ios: 30%, //30 percent of margin is applied to IOS
            android:10%, // 30 percent of margin is applied to Andriod

          })}}>

Go to this website by React-native: https://reactnative.dev/docs/platform-specific-code for more information.

Leave a Reply

Your email address will not be published.