I have a TouchableOpacity
with a background color that I want to change depending on a condition.
In this question they answer how to do it, by controlling the style in the state
<TouchableOpacity
style={{backgroundColor:this.state.backgroundColor}}
>
In my case, my TouchableOppacity has many style properties, and to keep the code clean I don't want to define all of them inside my render function, since most of them don't depend on any condition.
Usually I do:
<TouchableOpacity style={styles.button}>
// and then at the end of the file I define the styles
const styles = StyleSheet.create({
button: {
borderRadius: 15,
width: 200,
height: 50,
margin: 20,
alignItems: "center",
justifyContent: "center"
}
}
Now I need to combine both, being able to set the backgroundColor from the state and the rest of the properties from the styles.button
at the end of the file.
Is there a way to combine styles from different places, so I can have the static ones defined at the end of the file and the dynamic ones inside my class?
I tried something like:
<TouchableOpacity style={{backgroundColor: this.state.backgroundColor}, styles.button}>
But although it sets the styles.button property correctly it doesn't set the backgroundColor.
You can achieve this by below code: