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.
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)
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%'
}
}
});
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: {
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With