Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Access State from StyleSheet

Tags:

react-native

I am trying to set the background of a container based on the state but it keeps showing me an error bg is not defined

constructor(props) {
    super(props)
    this.state = {
        bg:'#fff'
    }
}

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

const styles = StyleSheet.create({
    container:{
        flex: 1,
        backgroundColor: this.state.bg,
    }
})
like image 395
Basil Satti Avatar asked Aug 03 '26 19:08

Basil Satti


2 Answers

Change this code:

return <View style={[styles.container, backgroundColor: this.state.bg]}/>

for this code:

return <View style={[styles.container, {backgroundColor: this.state.bg}]}/>
like image 71
josecastillo86 Avatar answered Aug 05 '26 21:08

josecastillo86


Please see my comment below and use like it

enter image description here

like image 22
Pramod Kumar Avatar answered Aug 05 '26 21:08

Pramod Kumar



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!