Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Platform conditional statements in stylesheets (react-native)

For minor platform specific code you can use the Platform module to execute some platform dependent code. As detailed in the docs here: https://facebook.github.io/react-native/docs/platform-specific-code.html

There is an example of how to use it in stylesheets

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

I would like to do something similar but a simple if statement to decide whether or not to use a style, for example one that is for one platform only.

Here is an example:

var styles = StyleSheet.create({
   textInputStyle: {
      if (Platform.OS === 'android') {
         textAlignVertical:'top' // android only style
      }
   }
});~

This is syntactically incorrect, what's the correct code to achieve this. I would like to avoid having two separate style sheets for each Platform as it seems unnecessary when it's only 1 or 2 fields that are different.

like image 296
Mark Silver Avatar asked Mar 10 '16 12:03

Mark Silver


3 Answers

I believe this is what you are looking for:

var styles = StyleSheet.create({
   textInputStyle: {
      ...Platform.select({
        ios: {
            //
        },
        android: {
            //
        },
    }),
   }
})

The link you provided shows the above code as an example. (v0.59)

like image 85
Jovan Avatar answered Oct 11 '22 23:10

Jovan


Please have a look on react-native-extended-stylesheet that supports media queries allowing you to define styles for particular platform / screen.

For example:

import EStyleSheet from 'react-native-extended-stylesheet';

...

render() {
  return (
    <View style={styles.column}></View>
  );
}

...

const styles = EStyleSheet.create({
    '@media ios': {
      column: {
        width: '80%'
      }
    },
    '@media android': {
      column: {
        width: '90%'
      }
    }
});

You can also use it for particular style items:

const styles = EStyleSheet.create({
   column: {
      '@media ios': {
         width: '80%'
      },
      '@media android': {
         width: '90%'
      }
   }
});
like image 40
vitalets Avatar answered Oct 12 '22 00:10

vitalets


One way to achieve is to have both different styles and then apply it dynamically in render. For ex:

render(){
  let platformStyle = Platform.OS === 'ios' ? styles.iosStyle: styles.androidStyle;
  return (<View style={platformStyle}>
          .....
          </View>);
  }
  .....
  const styles = StyleSheet.create({
    iosStyle: {
    },
    androidStyle: {

    }
  });
like image 43
agenthunt Avatar answered Oct 11 '22 22:10

agenthunt