Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we check a style attribute of a react-native app?

I wanted to check whether color is white of an element, as follows,

if(styles.background=='white')
console.log("ok")

console.log(styles.background=='white') --> was false [1]

why [1] returns false?

like image 927
Dinuka Salwathura Avatar asked Nov 29 '25 14:11

Dinuka Salwathura


2 Answers

In your case styles is a StyleSheet object.

You need to use the StyleSheet.flatten function as below:

 const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF'
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
});

var styleObj = StyleSheet.flatten([styles.container])

console.warn(styleObj.backgroundColor==='#F5FCFF') //=>true

To process a prop style of a component you could use it as below:

 let backgroundColor = Stylesheet.flatten(this.props.style).backgroundColor;

You can find the source code of the function here:

https://github.com/facebook/react-native/blob/master/Libraries/StyleSheet/flattenStyle.js

Sources and more details here:

https://facebook.github.io/react-native/docs/stylesheet.html

https://stackoverflow.com/a/35233409/1979861

like image 151
Florin Dobre Avatar answered Dec 02 '25 02:12

Florin Dobre


Just want to make sure the parameter passing syntax is correct.
(Note: the square brackets surrounding the parameter are not needed.)

For single form style sheet:

var styleObj = StyleSheet.flatten(styles.container)

For multiple-form style sheet:

var styleObj = StyleSheet.flatten(styles[1].container)

Then you can print it as a dict to exam the attributes:

console.log(styleObj)
like image 21
朱梅寧 Avatar answered Dec 02 '25 03:12

朱梅寧



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!