Hossam Ghareeb Hossam Ghareeb - 16 days ago 5
React JSX Question

Accessing state value from StyleSheet.create in ReactNative

I'm new in ReactNative and I have the following components:

<View style={{flex: 1}}>
<View style={styles.container}>
<Animated.Image style= {styles.photo}
source={{uri: this.props.user.picture.large}}/>
</View>
<View style={{backgroundColor:'whitesmoke', flex: 1}}></View>
</View>


In the styles, I have the following:

const styles = StyleSheet.create({
container: {
flex: 0.5,
backgroundColor: '#4dbce9',
alignItems: 'center',
},
photo: {
height: 150,
width: 150,
borderRadius: 75,
borderWidth: 3,
borderColor: 'white',
transform: [ // `transform` is an ordered array
{scale: this.state.profileImgBounceVal},
]
}
});


I got an error when I access
this.state.profileImgBounceVal
as its outside the component I know. Is there any workaround for this except including the styles inside the
Animated.Image
tag?

Answer

You could use Stylesheet.flatten() to create a reusable style object in your component:

var animatedImageStyle = StyleSheet.flatten([
  styles.photo,
  {
    transform: [{scale:this.state.profileImgBounceVal}]
  }
])

<View style={{flex: 1}}>
  <View style={styles.container}>
    <Animated.Image style={animatedImageStyle}
            source={{uri: this.props.user.picture.large}}/>
  </View>
  <View style={{backgroundColor:'whitesmoke', flex: 1}}></View>
</View>