Basil Satti
Basil Satti

Reputation: 700

React Native Access State from StyleSheet

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,
    }
})

Upvotes: 7

Views: 4775

Answers (3)

josecastillo86
josecastillo86

Reputation: 330

Change this code:

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

for this code:

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

Upvotes: 6

Pramod Kumar
Pramod Kumar

Reputation: 129

Please see my comment below and use like it

enter image description here

Upvotes: 1

Blimeys
Blimeys

Reputation: 176

You cannot really, however what you can do is use it within the style of the container like so:

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

const styles = StyleSheet.create({
    container:{
        flex:1
    }})
render(){
  return <View style={[styles.container, backgroundColor: this.state.bg]}/>
} 

Upvotes: 0

Related Questions